码迷,mamicode.com
首页 > 其他好文 > 详细

数据结构-线性表

时间:2015-05-17 22:00:34      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:

数据结构-线性表

线性表是n个数据元素的有限序列。n为线性表的长度,n=0时称为空表。在非空表中的每个数据元素都有一个确定的位置。

一般具有一下操作:

clear Removes all of the elements from this list (optional operation).

 

isEmpty Returns true if this list contains no elements.

 

size Returns the number of elements in this list.

 

get Returns the element at the specified position in this list.

 

set Replaces the element at the specified position in this list with the specified element (optional operation).

 

add  Appends the specified element to the end of this list (optional operation).

Inserts the specified element at the specified position in this list (optional operation).

 

contains Returns true if this list contains the specified element.

 

equals Compares the specified object with this list for equality.

 

iterator Returns an iterator over the elements in this list in proper sequence.

 

remove Removes the first occurrence of the specified element from this list, if it is present (optional operation).

 

indexOf Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.

 

lastIndexOf Returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element.

 

sort  Sorts this list according to the order induced by the specified Comparator.

 

addAll Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection‘s iterator (optional operation).

 

containsAll Returns true if this list contains all of the elements of the specified collection.

 

removeAll Removes from this list all of its elements that are contained in the specified collection (optional operation).

 

replaceAll Replaces each element of this list with the result of applying the operator to that element. @since  1.8

 

retainAll Retains only the elements in this list that are contained in the specified collection (optional operation).

 

spliterator Creates a Spliterator over the elements in this list. @since  1.8

 

subList Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.

 

toArray Returns an array containing all of the elements in this list in proper sequence (from first to last element).

 

 

java中,List是一个接口,而ArrayList是一个ArrayList是接口List的一个实现

所以List不能被构造,但可以向上面那样为List建一个引用,而ArrayList就可以被构造。

List list;     // list=null;

List list = new ArrayList();建了一个ArrayList象后把它的引用赋值给List时,它是一个List象了, ArrayList的独自(List没有的属性和方法就不能再用了,强制型变换后才能再用 ArrayList list=new ArrayList();建一保留了ArrayList的所有属性。

 

实例

import java.util.*;

import java.util.ArrayList;

import java.util.List;

 

public class TestList{

         public static void main(String[] args){

                   List<Object> list = new ArrayList<Object>();

                   ArrayList<Object> arrayList = new ArrayList<Object>();

                   // list.trimToSize(); //错误,没有方法。

                   arrayList.trimToSize();   //ArrayList里有方法。

         }

}

 

List接口的常用实现类ArrayListLinkedList,在使用List集合,通常情况下声明List型,例化根据实际情况的需要,例化ArrayListLinkedList,例如:

List<String> l = new ArrayList<String>();// 利用ArrayList类实例化List集合

List<String> l2 = new LinkedList<String>();// 利用LinkedList类实例化List集合

 

其中,add(int index, Object obj)方法和set(int index, Object obj)方法的区

在使用List需要注意区分add(int index, Object obj)方法和set(int index, Object obj)方法,前者是向指定索引位置添加象,而后者是修改指定索引位置的

 

实例

import java.util.Iterator;

import java.util.LinkedList;

import java.util.List;

 

public class TestCollection {

 

         public static void main(String[] args) {

                   String a = "A", b = "B", c = "C", d = "D", e = "E";

                   List<String> list = new LinkedList<String>();

 

                   list.add(a);

                   list.add(e);

                   list.add(d);

 

                   list.set(1, b);// 将索引位置1e修改为对b

                   list.add(2, c);// c添加到索引位置2的位置

 

                   Iterator<String> it = list.iterator();

                   while (it.hasNext()) {

                            System.out.println(it.next());

                   }

         }

}

在控制台将出如下信息:

A

B

C

D

 

从以上内容看不出数据结构的什么来是吧,下面贴出Java1.8ArrayList的源代码。出于篇幅,有所删减。

-------------------------

public class ArrayList<E> extends AbstractList<E>

        implements List<E>, RandomAccess, Cloneable, java.io.Serializable

{

 

    transient Object[] elementData; // non-private to simplify nested class access

    private int size;

 

    /**

     * Constructs an empty list with an initial capacity of ten.

     */

    public ArrayList() {

        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;

    }

 

    /**

     * Removes all of the elements from this list.  The list will

     * be empty after this call returns.

     */

    public void clear() {

        modCount++;

 

        // clear to let GC do its work

        for (int i = 0; i < size; i++)

            elementData[i] = null;

 

        size = 0;

    }

 

    /**

     * Returns <tt>true</tt> if this list contains no elements.

     *

     * @return  <tt>true</tt> if this list contains no elements

     */

    public boolean isEmpty() {

        return size == 0;

    }

 

    /**

     * Returns the number of elements in this list.

     *

     * @return  the number of elements in this list

     */

    public int size() {

        return size;

    }

 

    @SuppressWarnings("unchecked")

    E elementData(int index) {

        return (E) elementData[index];

    }

 

    /**

     * Returns the element at the specified position in this list.

     *

     * @param  index index of the element to return

     * @return the element at the specified position in this list

     * @throws IndexOutOfBoundsException {@inheritDoc}

     */

    public E get(int index) {

        rangeCheck(index);

 

        return elementData(index);

    }

 

    /**

     * Replaces the element at the specified position in this list with

     * the specified element.

     *

     * @param index index of the element to replace

     * @param element element to be stored at the specified position

     * @return the element previously at the specified position

     * @throws IndexOutOfBoundsException {@inheritDoc}

     */

    public E set(int index, E element) {

        rangeCheck(index);

 

        E oldValue = elementData(index);

        elementData[index] = element;

        return oldValue;

    }

 

 

    /**

     * Appends the specified element to the end of this list.

     *

     * @param e element to be appended to this list

     * @return <tt>true</tt> (as specified by {@link Collection#add})

     */

    public boolean add(E e) {

        ensureCapacityInternal(size + 1);  // Increments modCount!!

        elementData[size++] = e;

        return true;

    }

 

    /**

     * Inserts the specified element at the specified position in this

     * list. Shifts the element currently at that position (if any) and

     * any subsequent elements to the right (adds one to their indices).

     *

     * @param index index at which the specified element is to be inserted

     * @param element element to be inserted

     * @throws IndexOutOfBoundsException {@inheritDoc}

     */

    public void add(int index, E element) {

        rangeCheckForAdd(index);

 

        ensureCapacityInternal(size + 1);  // Increments modCount!!

        System.arraycopy(elementData, index, elementData, index + 1,

                         size - index);

        elementData[index] = element;

        size++;

    }

 

    /**

     * Returns <tt>true</tt> if this list contains the specified element.

     * More formally, returns <tt>true</tt> if and only if this list contains

     * at least one element <tt>e</tt> such that

     * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>.

     *

     * @param o element whose presence in this list is to be tested

     * @return <tt>true</tt> if this list contains the specified element

     */

    public boolean contains(Object o) {

        return indexOf(o) >= 0;

    }

 

    /**

     * Returns an iterator over the elements in this list in proper sequence.

     *

     * <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>.

     *

     * @return an iterator over the elements in this list in proper sequence

     */

    public Iterator<E> iterator() {

        return new Itr();

    }

    private class Itr implements Iterator<E> {

       

    }

 

    /**

     * Removes the element at the specified position in this list.

     * Shifts any subsequent elements to the left (subtracts one from their

     * indices).

     *

     * @param index the index of the element to be removed

     * @return the element that was removed from the list

     * @throws IndexOutOfBoundsException {@inheritDoc}

     */

    public E remove(int index) {

        rangeCheck(index);

 

        modCount++;

        E oldValue = elementData(index);

 

        int numMoved = size - index - 1;

        if (numMoved > 0)

            System.arraycopy(elementData, index+1, elementData, index,

                             numMoved);

        elementData[--size] = null; // clear to let GC do its work

 

        return oldValue;

    }

 

    /**

     * Removes the first occurrence of the specified element from this list,

     * if it is present.  If the list does not contain the element, it is

     * unchanged.  More formally, removes the element with the lowest index

     * <tt>i</tt> such that

     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>

     * (if such an element exists).  Returns <tt>true</tt> if this list

     * contained the specified element (or equivalently, if this list

     * changed as a result of the call).

     *

     * @param o element to be removed from this list, if present

     * @return <tt>true</tt> if this list contained the specified element

     */

    public boolean remove(Object o) {

        if (o == null) {

            for (int index = 0; index < size; index++)

                if (elementData[index] == null) {

                    fastRemove(index);

                    return true;

                }

        } else {

            for (int index = 0; index < size; index++)

                if (o.equals(elementData[index])) {

                    fastRemove(index);

                    return true;

                }

        }

        return false;

    }

 

    /*

     * Private remove method that skips bounds checking and does not

     * return the value removed.

     */

    private void fastRemove(int index) {

        modCount++;

        int numMoved = size - index - 1;

        if (numMoved > 0)

            System.arraycopy(elementData, index+1, elementData, index,

                             numMoved);

        elementData[--size] = null; // clear to let GC do its work

    }

 

    /**

     * Returns the index of the first occurrence of the specified element

     * in this list, or -1 if this list does not contain the element.

     * More formally, returns the lowest index <tt>i</tt> such that

     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,

     * or -1 if there is no such index.

     */

    public int indexOf(Object o) {

        if (o == null) {

            for (int i = 0; i < size; i++)

                if (elementData[i]==null)

                    return i;

        } else {

            for (int i = 0; i < size; i++)

                if (o.equals(elementData[i]))

                    return i;

        }

        return -1;

    }

 

    /**

     * Returns the index of the last occurrence of the specified element

     * in this list, or -1 if this list does not contain the element.

     * More formally, returns the highest index <tt>i</tt> such that

     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,

     * or -1 if there is no such index.

     */

    public int lastIndexOf(Object o) {

        if (o == null) {

            for (int i = size-1; i >= 0; i--)

                if (elementData[i]==null)

                    return i;

        } else {

            for (int i = size-1; i >= 0; i--)

                if (o.equals(elementData[i]))

                    return i;

        }

        return -1;

    }

 

    @Override

    @SuppressWarnings("unchecked")

    public void sort(Comparator<? super E> c) {

        final int expectedModCount = modCount;

        Arrays.sort((E[]) elementData, 0, size, c);

        if (modCount != expectedModCount) {

            throw new ConcurrentModificationException();

        }

        modCount++;

    }

 

    /**

     * Appends all of the elements in the specified collection to the end of

     * this list, in the order that they are returned by the

     * specified collection‘s Iterator.  The behavior of this operation is

     * undefined if the specified collection is modified while the operation

     * is in progress.  (This implies that the behavior of this call is

     * undefined if the specified collection is this list, and this

     * list is nonempty.)

     *

     * @param c collection containing elements to be added to this list

     * @return <tt>true</tt> if this list changed as a result of the call

     * @throws NullPointerException if the specified collection is null

     */

    public boolean addAll(Collection<? extends E> c) {

        Object[] a = c.toArray();

        int numNew = a.length;

        ensureCapacityInternal(size + numNew);  // Increments modCount

        System.arraycopy(a, 0, elementData, size, numNew);

        size += numNew;

        return numNew != 0;

    }

 

    /**

     * Removes from this list all of its elements that are contained in the

     * specified collection.

     *

     * @param c collection containing elements to be removed from this list

     * @return {@code true} if this list changed as a result of the call

     * @throws ClassCastException if the class of an element of this list

     *         is incompatible with the specified collection

     * (<a href="Collection.html#optional-restrictions">optional</a>)

     * @throws NullPointerException if this list contains a null element and the

     *         specified collection does not permit null elements

     * (<a href="Collection.html#optional-restrictions">optional</a>),

     *         or if the specified collection is null

     * @see Collection#contains(Object)

     */

    public boolean removeAll(Collection<?> c) {

        Objects.requireNonNull(c);

        return batchRemove(c, false);

    }

 

    /**

     * Retains only the elements in this list that are contained in the

     * specified collection.  In other words, removes from this list all

     * of its elements that are not contained in the specified collection.

     *

     * @param c collection containing elements to be retained in this list

     * @return {@code true} if this list changed as a result of the call

     * @throws ClassCastException if the class of an element of this list

     *         is incompatible with the specified collection

     * (<a href="Collection.html#optional-restrictions">optional</a>)

     * @throws NullPointerException if this list contains a null element and the

     *         specified collection does not permit null elements

     * (<a href="Collection.html#optional-restrictions">optional</a>),

     *         or if the specified collection is null

     * @see Collection#contains(Object)

     */

    public boolean retainAll(Collection<?> c) {

        Objects.requireNonNull(c);

        return batchRemove(c, true);

    }

 

    private boolean batchRemove(Collection<?> c, boolean complement) {

        final Object[] elementData = this.elementData;

        int r = 0, w = 0;

        boolean modified = false;

        try {

            for (; r < size; r++)

                if (c.contains(elementData[r]) == complement)

                    elementData[w++] = elementData[r];

        } finally {

            // Preserve behavioral compatibility with AbstractCollection,

            // even if c.contains() throws.

            if (r != size) {

                System.arraycopy(elementData, r,

                                 elementData, w,

                                 size - r);

                w += size - r;

            }

            if (w != size) {

                // clear to let GC do its work

                for (int i = w; i < size; i++)

                    elementData[i] = null;

                modCount += size - w;

                size = w;

                modified = true;

            }

        }

        return modified;

    }

 

    @Override

    @SuppressWarnings("unchecked")

    public void replaceAll(UnaryOperator<E> operator) {

        Objects.requireNonNull(operator);

        final int expectedModCount = modCount;

        final int size = this.size;

        for (int i=0; modCount == expectedModCount && i < size; i++) {

            elementData[i] = operator.apply((E) elementData[i]);

        }

        if (modCount != expectedModCount) {

            throw new ConcurrentModificationException();

        }

        modCount++;

    }

 

    /**

     * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>

     * and <em>fail-fast</em> {@link Spliterator} over the elements in this

     * list.

     *

     * <p>The {@code Spliterator} reports {@link Spliterator#SIZED},

     * {@link Spliterator#SUBSIZED}, and {@link Spliterator#ORDERED}.

     * Overriding implementations should document the reporting of additional

     * characteristic values.

     *

     * @return a {@code Spliterator} over the elements in this list

     * @since 1.8

     */

    @Override

    public Spliterator<E> spliterator() {

        return new ArrayListSpliterator<>(this, 0, -1, 0);

    }

 

    /**

     * Returns a view of the portion of this list between the specified

     * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.  (If

     * {@code fromIndex} and {@code toIndex} are equal, the returned list is

     * empty.)  The returned list is backed by this list, so non-structural

     * changes in the returned list are reflected in this list, and vice-versa.

     * The returned list supports all of the optional list operations.

     *

     * <p>This method eliminates the need for explicit range operations (of

     * the sort that commonly exist for arrays).  Any operation that expects

     * a list can be used as a range operation by passing a subList view

     * instead of a whole list.  For example, the following idiom

     * removes a range of elements from a list:

     * <pre>

     *      list.subList(from, to).clear();

     * </pre>

     * Similar idioms may be constructed for {@link #indexOf(Object)} and

     * {@link #lastIndexOf(Object)}, and all of the algorithms in the

     * {@link Collections} class can be applied to a subList.

     *

     * <p>The semantics of the list returned by this method become undefined if

     * the backing list (i.e., this list) is <i>structurally modified</i> in

     * any way other than via the returned list.  (Structural modifications are

     * those that change the size of this list, or otherwise perturb it in such

     * a fashion that iterations in progress may yield incorrect results.)

     *

     * @throws IndexOutOfBoundsException {@inheritDoc}

     * @throws IllegalArgumentException {@inheritDoc}

     */

    public List<E> subList(int fromIndex, int toIndex) {

        subListRangeCheck(fromIndex, toIndex, size);

        return new SubList(this, 0, fromIndex, toIndex);

    }

 

    static void subListRangeCheck(int fromIndex, int toIndex, int size) {

        if (fromIndex < 0)

            throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);

        if (toIndex > size)

            throw new IndexOutOfBoundsException("toIndex = " + toIndex);

        if (fromIndex > toIndex)

            throw new IllegalArgumentException("fromIndex(" + fromIndex +

                                               ") > toIndex(" + toIndex + ")");

    }

 

    private class SubList extends AbstractList<E> implements RandomAccess {

       

    }

 

 

    /**

     * Returns an array containing all of the elements in this list

     * in proper sequence (from first to last element).

     *

     * <p>The returned array will be "safe" in that no references to it are

     * maintained by this list.  (In other words, this method must allocate

     * a new array).  The caller is thus free to modify the returned array.

     *

     * <p>This method acts as bridge between array-based and collection-based

     * APIs.

     *

     * @return an array containing all of the elements in this list in

     *         proper sequence

     */

    public Object[] toArray() {

        return Arrays.copyOf(elementData, size);

    }

 

    /**

     * Returns an array containing all of the elements in this list in proper

     * sequence (from first to last element); the runtime type of the returned

     * array is that of the specified array.  If the list fits in the

     * specified array, it is returned therein.  Otherwise, a new array is

     * allocated with the runtime type of the specified array and the size of

     * this list.

     *

     * <p>If the list fits in the specified array with room to spare

     * (i.e., the array has more elements than the list), the element in

     * the array immediately following the end of the collection is set to

     * <tt>null</tt>.  (This is useful in determining the length of the

     * list <i>only</i> if the caller knows that the list does not contain

     * any null elements.)

     *

     * @param a the array into which the elements of the list are to

     *          be stored, if it is big enough; otherwise, a new array of the

     *          same runtime type is allocated for this purpose.

     * @return an array containing the elements of the list

     * @throws ArrayStoreException if the runtime type of the specified array

     *         is not a supertype of the runtime type of every element in

     *         this list

     * @throws NullPointerException if the specified array is null

     */

    @SuppressWarnings("unchecked")

    public <T> T[] toArray(T[] a) {

        if (a.length < size)

            // Make a new array of a‘s runtime type, but my contents:

            return (T[]) Arrays.copyOf(elementData, size, a.getClass());

        System.arraycopy(elementData, 0, a, 0, size);

        if (a.length > size)

            a[size] = null;

        return a;

    }

}

-------------------------


数据结构-线性表

标签:

原文地址:http://my.oschina.net/u/660460/blog/415964

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!