Java 集合(二)List详解

  List是一种特殊的集合形式,该类型允许集合内元素有序、可重复
  在List模块的学习中,可以主要关注6个类(或接口),主要继承关系如下:

  这6个就是要基本掌握的所有List所有内容。

一、List

  List是一个接口(interface),继承Collection接口。
  List特点:
   1>是一个有序的、可重复的集合,集合中每一个元素都有对应的顺序索引。
   2>允许加入重复元素是应为可以通过索引来访问指定位置的元素。
   3>默认按照元素的添加顺序增加元素的索引。

1.1 添加元素

  1>public void add(int index, E element)
   在列表的指定位置插入指定元素。
  2>public boolean add(E object)
   向列表的尾部添加指定的元素,添加成功则返回true。
  3>public boolean addAll(int index, Collection<? extends E> collection)
   将指定 collection 中的所有元素都插入到列表中的指定位置,添加成功则返回true。
  4>public boolean addAll(Collection<? extends E> collection)
   添加指定 collection 中的所有元素到此列表的结尾,添加成功则返回true。

1.2 删除元素

  1>public E remove(int location)
   移除并返回列表中指定位置的元素。
  2>public boolean remove(Object object)
   从此列表中移除第一次出现的指定元素。更确切地讲,移除满足 (object == null ? get(i)==null : object.equals(get(i))) 的最低索引 i 的元素,移除成功则返回true。
  3>public boolean removeAll(Collection<?> collection)
   从列表中移除指定 collection 中包含的其所有元素。
  4>public void clear()
   从列表中移除所有元素。

1.3 遍历元素

  1>public Iterator iterator()
   返回此列表元素的列表迭代器.
  2>public ListIterator listIterator()
   返回此列表元素的列表迭代器。
  3>public ListIterator listIterator(int index)
   返回列表中元素的列表迭代器,从列表的指定位置开始。

1.4 判断包含关系

  1>public boolean contains(Object object)
   如果列表包含指定的元素,则返回 true。更确切地讲,当且仅当列表包含满足(object == null ? object == null : object.equals(e)) 的元素 e 时才返回 true。
  2>public boolean containsAll(Collection<?> collection)
   如果列表包含指定 collection 的所有元素,则返回 true。

1.5 检索元素

  1>public int indexOf(Object object)
   返回此列表中第一次出现的指定元素的索引;如果此列表不包含该元素,则返回-1。更确切地讲,返回满足 (object==null ? get(i) == null : object.equals(get(i))) 的最低索引 i;如果没有这样的索引,则返回 -1。
  2>public int lastIndexOf(Object object)
   返回此列表中最后出现的指定元素的索引;如果列表不包含此元素,则返回 -1。更确切地讲,返回满足 (object == null ? get(i)==null : object.equals(get(i))) 的最高索引 i;如果没有这样的索引,则返回 -1。

1.6 其他方法

  1>public boolean equals(Object object)
   比较指定的对象与列表是否相等。当且仅当指定的对象也是一个列表、两个列表
有相同的大小,并且两个列表中的所有相应的元素对相等 时才返回 true( 如果
(e1 == null ? e2 == null :e1.equals(e2)),则两个元素 e1 和 e2 是相等 的)。
  2>public E get(int index)
   返回列表中指定位置的元素。
  3>public int hashCode()
   返回列表的哈希码值。
  4>public boolean retainAll(Collection<?> collection)
   仅在列表中保留指定 collection 中所包含的元素,即是否有交集,有交集则返回true。
  5>public E set(int location, E object)
   用指定元素替换列表中指定位置的元素。
  6>public int size()
   返回列表中的元素数。如果列表包含多于 Integer.MAX_VALUE 个元素,则返回 Integer.MAX_VALUE。
  7>public boolean isEmpty()
   如果列表不包含元素,则返回 true。
  8>public List subList(int start, int end)
   返回列表中指定的 start(包括 )和 end(不包括)之间的部分视图。
  9>public Object[ ] toArray()
   返回按适当顺序包含列表中的所有元素的数组。
  10>public T[ ] toArray(T[ ] array)
   返回指定类型的、包含该collection元素的数组。

二、AbstractList

  AbstractList是一个抽象类,继承AbstractCollection类,实现List接口。
  AbstractList实现了 List 的一些位置相关操作(比如 get,set,add,remove),是第一个实现随机访问方法的集合类,但不支持添加和替换。

2.1 添加元素

  1>public void add(int location, E object)
   在列表的指定位置插入指定元素。
  2>public boolean add(E object)
   在列表末尾插入指定元素。
  3>public boolean addAll(int location, Collection<? extends E> collection)
   将指定 collection 中的所有元素都插入到列表中的指定位置。

2.2 删除元素

  1>public E remove(int location)
   移除列表中指定位置的元素。
  2>protected void removeRange(int start, int end)
   从此列表中移除索引在 start(包括)和 end(不包括)之间的所有元素(如果 start == end,则此操作无效)。
  3>public void clear()
   从此列表中移除所有元素。

2.3 遍历元素

  1>public Iterator iterator()
   返回一个迭代器。
  2>public ListIterator listIterator()
   返回此列表元素的列表迭代器。
  3>public ListIterator listIterator(int location)
   返回列表中元素的列表迭代器。

2.4 检索元素

  1>public int indexOf(Object object)
   返回此列表中第一次出现的指定元素的索引。如果此列表不包含该元素,则返回 -1。更确切地讲,返回满足 (o==null ? get(i) == null : o.equals(get(i))) 的最低索引 i;如果没有这样的索引,则返回 -1。
  2>public int lastIndexOf(Object object)
   返回此列表中最后出现的指定元素的索引。如果列表不包含此元素,则返回 -1。更确切地讲,返回满足 (object == null ? get(i) == null : object.equals(get(i))) 的最高索引 i;如果没有这样的索引,则返回 -1。

2.5 其他方法

  1>public boolean equals(Object object)
   当且仅当指定的对象也是一个列表,两个列表具有相同的大小,而且两个列表中所有相应的元素对都相等 时,才返回 true(如果 (e1 == null ? e2 == null : e1.equals(e2)),则元素 e1 和 e2 相等)。
  2>public abstract E get(int location)
   返回列表中指定位置的元素。
  3>public int hashCode()
   返回此列表的哈希码值。
  4>public E set(int location, E object)
   用指定元素替换列表中指定位置的元素。
  5>public List subList(int start, int end)
   返回列表中指定的 start(包括 )和 end(不包括)之间的部分视图(如果 start和 end相等,则返回的列表为空)。

2.6 特殊方法

  1、add相关方法
   AbstractList中并没有实现add方法,所以需要先实现add方法,才能调用add相关的方法。public void add(int location, E object)方法具体代码如下:

    public void add(int location, E object) {
        throw new UnsupportedOperationException();
    }

  2、remove相关方法
   与add相关方法相似,AbstractList中也没有实现remove方法,所以需要先实现remove方法,才能调用remove相关的方法。public E remove(int location)方法具体代码如下:

    public E remove(int location) {
        throw new UnsupportedOperationException();
    }

  3、get方法
   AbstractList是抽象类,get就是类中的抽象方法,需要子类去实现,抽象方法为:

   public abstract E get(int location)

  4、set方法
   AbstractList中,set方法其实也是需要子类去实现的,public E set(int location, E object)方法具体代码如下:

    public E set(int location, E object) {
        throw new UnsupportedOperationException();
    }

三、LinkedList

  此类实现List接口,提供了List 接口的链表实现
  LinkedList特点:
   1>LinkedList 是一个继承于AbstractSequentialList的双向链表。它也可以被当作堆栈、队列或双端队列进行操作。
   2>LinkedList 实现 List 接口,能对它进行队列操作。
   3>LinkedList 实现 Deque 接口,即能将LinkedList当作双端队列使用。
   4>LinkedList 实现了Cloneable接口,即覆盖了函数clone(),能克隆。
   5>LinkedList 实现java.io.Serializable接口,这意味着LinkedList支持序列化,能通过序列化去传输。
   6>LinkedList 是非同步的。

3.1 构造方法

  1>public LinkedList()
   构造一个空链表。
  2>public LinkedList(Collection<? extends E> collection)
   构造一个包含指定 collection 中的元素的列表。

3.2 添加元素

  1>public void add(int location, E object)
   在此列表中指定的位置插入指定的元素。
  2>public boolean add(E object)
   在链表末尾添加元素。
  3>public boolean addAll(int location, Collection<? extends E> collection)
   将集合中的元素插入链表。
  4>public boolean addAll(Collection<? extends E> collection)
   将集合中的元素插入链表末尾。
  5>public void addFirst(E object)
   在链表头部添加元素。
  6>public void addLast(E object)
   在链表尾部添加元素。
  7>public boolean offerFirst(E e)
   在列表的开头插入指定的元素。
  8>public boolean offerLast(E e)
   在此列表末尾插入指定的元素。
  9>public boolean offer(E o)
   将指定元素添加到此列表的末尾。
  10>public void push(E e)
   将元素推入此列表所表示的堆栈。

3.3 删除元素

  1>public E remove(int location)
   移除指定位置元素。
  2>public boolean remove(Object object)
   移除第一个出现的指定元素。
  3>public E removeFirst()
   移除第一个元素 。
  4>public E removeLast()
   移除最后一个元素。
  5>public E pop()
   从此列表所表示的堆栈处弹出一个元素。
  6>public boolean removeFirstOccurrence(Object o)
   从此列表中移除第一次出现的指定元素。
  7>public boolean removeLastOccurrence(Object o)
   从此列表中移除最后一次出现的指定元素。
  8>public void clear()
   清空链表。

3.4 获取元素

  1>public E get(int location)
   获取对应位置的元素。
  2>public E getFirst()
   获取第一个元素。
  3>public E getLast()
   获取最后一个元素。
  4>public int indexOf(Object object)
   检索元素位置。
  5>public int lastIndexOf(Object object)
   返回元素最后一次出现的位置。
  6>public E peekFirst()
   获取但不移除此列表的第一个元素;如果此列表为空,则返回 null。
  7>public E peekLast()
   获取但不移除此列表的最后一个元素。
  8>public E pollFirst()
   获取并移除此列表的第一个元素。
  9>public E pollLast()
   获取并移除此列表的最后一个元素。
  10>public E set(int location, E object)
   将此列表中指定位置的元素替换为指定的元素。
  11>public E poll()
   获取并移除此列表的头(第一个元素)。
  12>public E remove()
   获取并移除此列表的头(第一个元素)。
  13>public E peek()
   获取但不移除此列表的头(第一个元素)。
  14>public E element()
   获取但不移除此列表的头(第一个元素)。

3.5 其他方法

  1>public Object clone()
   克隆链表。
  2>public boolean contains(Object object)
   判断链表中是否包含某个元素。
  3>public ListIterator listIterator(int location)
   返回从指定位置开始的列表迭代器 。
  4>public Iterator descendingIterator()
   返回以逆向顺序在此双端队列的元素上进行迭代的迭代器。
  5>public int size()
   链表元素个数。
  6>public Object [ ] toArray()
   返回以适当顺序(从第一个元素到最后一个元素)包含此列表中所有元素的数组。
  7>public T[] toArray(T[ ] contents)
   返回包含当前链表元素、指定数组形式的数组。

3.6 特殊方法

  1、public void add(int location, E object)
   该方法的作用是在指定位置插入一个元素,源码如下:

    public void add(int location, E object) {
        if (location >= 0 && location <= size) {
            Link<E> link = voidLink;
            if (location < (size / 2)) {
                for (int i = 0; i <= location; i++) {
                    link = link.next;
                }
            } else {
                for (int i = size; i > location; i--) {
                    link = link.previous;
                }
            }
            Link<E> previous = link.previous;
            Link<E> newLink = new Link<E>(object, previous, link);
            previous.next = newLink;
            link.previous = newLink;
            size++;
            modCount++;
        } else {
            throw new IndexOutOfBoundsException();
        }
    }

   从上述代码可以看出,该方法的实现是:先检验location参数的合法性,不合法则抛出IndexOutOfBoundsException。合法的情况下,再检查该位置是在List的前半部还是在后半部,如果在前半部,则从前向后遍历,如果在后半部,则从后向前查找location位置。找到对应的位置后,用object创建一个新的节点,插入到List中,List元素个数size++。此处有意思的是modCount变量,该变量是用在fail-fast机制中的,由于LinkedList是线程不安全的,在多个线程中遍历List中的元素时,如果有某个线程修改了元素,就有可能产生不同的结果,该modCount变量相当于一个动态计数器,如果遍历时的元素个数与modCount不一致时,直接抛出异常,从而避免多个线程遍历产生不同的结果。
  2、public boolean addAll(int location, Collection<? extends E> collection)
   该方法的作用是在指定位置插入一个collection中的所有元素,其实现和上个方法相似,多加入了对collection元素个数的校验。
  3、public E remove(int location)
   其实remove的方法也很多,实现方式也与add方法相似,如删除固定的位置的一个元素:

    public E remove(int location) {
        if (location >= 0 && location < size) {
            Link<E> link = voidLink;
            if (location < (size / 2)) {
                for (int i = 0; i <= location; i++) {
                    link = link.next;
                }
            } else {
                for (int i = size; i > location; i--) {
                    link = link.previous;
                }
            }
            Link<E> previous = link.previous;
            Link<E> next = link.next;
            previous.next = next;
            next.previous = previous;
            size--;
            modCount++;
            return link.data;
        }
        throw new IndexOutOfBoundsException();
    }

3.7 常用遍历方法

  LinkedList常用的遍历方法有4种:Iterator遍历、ListIterator遍历、普通for循环和foreach循环。
   1>Iterator遍历,示例代码如下:

        Iterator<String> iterator=testLinkedList.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }

   1>ListIterator遍历,示例代码如下:

        ListIterator<String> listIterator=testLinkedList.listIterator();           
        while(listIterator.hasNext()){
             System.out.println(listIterator.next());       
        }

   3>普通for循环,示例代码如下:

        for(int i=0;i<testLinkedList.size();i++){
            System.out.println(testLinkedList.get(i));
        }

   4>foreach循环,示例代码如下:

        for(String str:testLinkedList){
            System.out.println(str);
        }

四、ArrayList

  ArrayList继承AbstractList,可以理解为实现了List接口的动态数组。
  ArrayList不是线程安全的,只能用在单线程环境下,多线程环境下可以考虑用Collections.synchronizedList(List l)函数返回一个线程安全的ArrayList类。

4.1 构造方法

  1>public ArrayList(int capacity)
    构造一个具有指定初始容量的空列表。
  2>public ArrayList( )
   构造一个初始容量为 10 的空列表。
  3>public ArrayList(Collection<? extends E> collection)
   构造一个包含指定 collection 的元素的列表。

4.2 添加元素

  1>public boolean add(E object)
   将指定的元素添加到此列表的尾部。
  2>public void add(int index, E object)
   将指定的元素插入此列表中的指定位置。
  3>public boolean addAll(Collection<? extends E> collection)
   按照指定 collection 的迭代器所返回的元素顺序,将该 collection 中的所有元素添加到此列表的尾部。
  4>public boolean addAll(int index, Collection<? extends E> collection)
   在指定的位置追加collection中的元素。

4.3 删除元素

  1>public E remove(int index)
   移除此列表中指定位置上的元素。
  2>public boolean remove(Object object)
   移除此列表中首次出现的指定元素(如果存在)。如果列表不包含此元素,则列表不做改动。更确切地讲,移除满足 (o == null ? get(i) == null : o.equals(get(i))) 的最低索引的元素(如果存在此类元素)。
  3>protected void removeRange(int fromIndex, int toIndex)
   移除列表中索引在 fromIndex(包括)和 toIndex(不包括)之间的所有元素。
  4>public void clear()
   移除此列表中的所有元素。

4.4 其他方法

  1>public Object clone()
   返回此 ArrayList 实例的浅表副本。
  2>public void ensureCapacity(int minimumCapacity)
   如有必要,增加此 ArrayList 实例的容量,以确保它至少能够容纳最小容量参数所指定的元素数。
  3>public E get(int index)
   返回此列表中指定位置上的元素。
  4>public int size()
   数组中元素数量。
  5>public boolean isEmpty()
   数组中元素个数是否为0。
  6>public boolean contains(Object object)
   如果此列表中包含指定的元素,则返回 true。更确切地讲,当且仅当此列表包含至少一个满足 (object == null ? e == null : object.equals(e)) 的元素 e 时,则返回 true。
  7>public int indexOf(Object object)
   返回此列表中首次出现的指定元素的索引,或如果此列表不包含元素,则返回 -1。更确切地讲,返回满足 (object==null ? get(i)==null : object.equals(get(i))) 的最低索引 i ,如果不存在此类索引,则返回 -1。
  8>public int lastIndexOf(Object object)
   返回此列表中最后一次出现的指定元素的索引,或如果此列表不包含索引,则返回 -1。更确切地讲,返回满足 (object == null ? get(i) == null : object.equals(get(i))) 的最高索引 i,如果不存在此类索引,则返回 -1。
  9>public E set(int index, E object)
   用指定的元素替代此列表中指定位置上的元素。
  10>public Object[ ] toArray()
   返回包含此列表中所有元素的数组。
  11>public T[ ] toArray(T[] contents)
   返回指定数组形式、包含该List的数组。
  12>public void trimToSize()
    将此 ArrayList 实例的容量调整为列表的当前大小。
  13>public Iterator iterator()
   返回一个迭代器。
  14>public int hashCode()
   返回哈希值。
  15>public boolean equals(Object o)
   List比较。

4.5 特殊方法

  1、public ArrayList(Collection<? extends E> collection)
   ArrayList有三种构造方法,空构造、指定容量构造和这种指定collection构造。这种构造方法的实现是:先将collection转换为数组,然后再将转换后的数组拷贝到指定数组中。
  2、public void add(int index, E object)
   该方法的作用是在指定位置插入一个元素,示例代码:

    public void add(int index, E object) {
        Object[] a = array;
        int s = size;
        if (index > s || index < 0) {
            throwIndexOutOfBoundsException(index, s);
        }

        if (s < a.length) {
            System.arraycopy(a, index, a, index + 1, s - index);
        } else {
            // assert s == a.length;
            Object[] newArray = new Object[newCapacity(s)];
            System.arraycopy(a, 0, newArray, 0, index);
            System.arraycopy(a, index, newArray, index + 1, s - index);
            array = a = newArray;
        }
        a[index] = object;
        size = s + 1;
        modCount++;
    }

   从上述代码可以看出,实现的逻辑为:先检测index参数的合法性,然后检查数组是否完全填满了元素(此处表明ArrayList是可以存储空元素的)。如果ArrayList未填满,直接插入指定元素,否则先扩容一个单位,再插入指定元素。
  3、private static int newCapacity(int currentCapacity)
   该方法的作用是对数组进行扩容,代码如下:

    private static int newCapacity(int currentCapacity) {
        int increment = (currentCapacity < (MIN_CAPACITY_INCREMENT / 2) ? MIN_CAPACITY_INCREMENT : currentCapacity >> 1);
        return currentCapacity + increment;
    }

   MIN_CAPACITY_INCREMENT是一个常量,值为12,。从上面可以看出,数组扩容需要先计算出一个增量increment,当数组原容量小于6时,增量为12,否则增量为原始容量的一半。
  4、public void ensureCapacity(int minimumCapacity)
   该方法的作用是确保ArrayList可以容纳minimumCapacity的元素,代码示例如下:

    public void ensureCapacity(int minimumCapacity) {
        Object[] a = array;
        if (a.length < minimumCapacity) {
            Object[] newArray = new Object[minimumCapacity];
            System.arraycopy(a, 0, newArray, 0, size);
            array = newArray;
            modCount++;
        }
    }

   从上面代码可以看出,实现为:判断当前ArrayList容量是否小于minimumCapacity,如果小于,则创建一个容量为minimumCapacity的数组,然后再把原来的元素拷贝过去,modCount自增1。
  5、public void trimToSize()
   该方法的作用是将ArrayList的容量变得和当前数组中元素的个数一样。代码如下:

    public void trimToSize() {
        int s = size;
        if (s == array.length) {
            return;
        }
        if (s == 0) {
            array = EmptyArray.OBJECT;
        } else {
            Object[] newArray = new Object[s];
            System.arraycopy(array, 0, newArray, 0, s);
            array = newArray;
        }
        modCount++;
    }

   由上述代码可知,有三种情况:数组中元素刚刚和ArrayList容量相等、数组中元素个数为零和数组中元素个数比容量小,然后对数组进行“缩容”,再拷贝原元素。
  6、public int hashCode()
   该方法的作用是求ArrayList中哈希值的综合,示例大吗如下:

    public int hashCode() {
        Object[] a = array;
        int hashCode = 1;
        for (int i = 0, s = size; i < s; i++) {
            Object e = a[i];
            hashCode = 31 * hashCode + (e == null ? 0 : e.hashCode());
        }
        return hashCode;
    }

   由上述代码可知,ArrayList的哈希值等于数组中每个非空元素的哈希值相加的总和*31。
  7、public boolean equals(Object o)
   该方法的作用是比较两个ArrayList是否相等,代码如下:

    public boolean equals(Object o) {
        if (o == this) {
            return true;
        }
        if (!(o instanceof List)) {
            return false;
        }
        List<?> that = (List<?>) o;
        int s = size;
        if (that.size() != s) {
            return false;
        }
        Object[] a = array;
        if (that instanceof RandomAccess) {
            for (int i = 0; i < s; i++) {
                Object eThis = a[i];
                Object ethat = that.get(i);
                if (eThis == null ? ethat != null : !eThis.equals(ethat)) {
                    return false;
                }
            }
        } else {  // Argument list is not random access; use its iterator
            Iterator<?> it = that.iterator();
            for (int i = 0; i < s; i++) {
                Object eThis = a[i];
                Object eThat = it.next();
                if (eThis == null ? eThat != null : !eThis.equals(eThat)) {
                    return false;
                }
            }
        }
        return true;
    }

   由上述代码可以看出复杂对象比较的一般思路:
    1>比较是否是同一对象。
    2>比较是否是同一类型。
    3>比较元素个数。
    4>比较是否是RandomAccess类型。
    5>逐个遍历元素,进行比较。

4.6 常用遍历方法

  ArrayList常用的遍历方法有3种:Iterator遍历、普通for循环和foreach循环。
   1>Iterator遍历,示例代码如下:

        Iterator<String> it = testList.iterator();
        while(it.hasNext()) {
           System.out.println(it.next());
        }

   2>普通for循环,示例代码如下:

        for(int i = 0 ; i < testList.size() ; i++){
            System.out.println(testList.get(i));
        }

   3>foreach循环,示例代码如下:

        for(String string:testList){
        	System.out.println(string);
        }

五、Vector

  Vector继承AbstractList,实现List接口。
  Vector特点:
   1>Vector 继承了AbstractList,实现了List接口。
   2>Vector实现了RandmoAccess接口,即提供了随机访问功能。
   3>Vector 实现了Cloneable接口,即实现克隆功能。
   4>Vector 实现Serializable接口,表示支持序列化。
  Vector是线程安全的。

5.1 构造方法

  1>public Vector()
   构造一个空向量,使其内部数据数组的大小为 10,其标准容量增量为零。
  2>public Vector(int capacity)
   使用指定的初始容量和等于零的容量增量构造一个空向量。
  3>public Vector(int capacity, int capacityIncrement)
   使用指定的初始容量和容量增量构造一个空的向量 。
  4>public Vector(Collection<? extends E> collection)
   构造一个包含指定 collection 中的元素的向量。

5.2 添加元素

  1>public void add(int location, E object)
   在向量的指定位置插入指定的元素。
  2>public synchronized boolean add(E object)
   将指定元素添加到此向量的末尾。
  3>public synchronized boolean addAll(int location, Collection<? extends E> collection)
   在指定位置将指定 Collection 中的所有元素插入到此向量中。
  4>public synchronized boolean addAll(Collection<? extends E> collection)
   将指定 Collection 中的所有元素添加到此向量的末尾,按照指定 collection 的迭代器所返回的顺序添加这些元素。
  5>public synchronized void addElement(E object)
   将指定的组件添加到此向量的末尾。

5.3 删除元素

  1>public synchronized E remove(int location)
   移除此向量中指定位置的元素。
  2>public boolean remove(Object object)
   移除此向量中指定元素的第一个匹配项,如果向量不包含该元素,则元素保持不变。更确切地讲,移除其索引 i 满足 (o == null ? get(i)==null : o.equals(get(i))) 的元素。
  3>public synchronized boolean removeAll(Collection<?> collection)
   从此向量中移除包含在指定 Collection 中的所有元素。
  4>public synchronized void removeAllElements()
   从此向量中移除全部组件,并将其大小设置为零。
  5>public synchronized boolean removeElement(Object object)
   从此向量中移除变量的第一个(索引最小的)匹配项。
  6>public synchronized void removeElementAt(int location)
   删除指定索引处的组件。
  7>public void clear()
   从此向量中移除所有元素。

5.4 删除元素

  1>public synchronized int capacity()
   返回此向量的当前容量。
  2>public synchronized Object clone()
   返回向量的一个副本。
  3>public boolean contains(Object object)
   如果此向量包含指定的元素,则返回 true。更确切地讲,当且仅当此向量至少包含一个满足 (o == null ? e == null : o.equals(e)) 的元素 e 时,返回 true。
  4>public synchronized boolean containsAll(Collection<?> collection)
    如果此向量包含指定 Collection 中的所有元素,则返回 true。
  5>public synchronized void copyInto(Object[ ] elements)
   将此向量的组件复制到指定的数组中。
  6>public synchronized E elementAt(int location)
   返回指定索引处的元素。
  7>public Enumeration elements()
   返回此向量的组件的枚举。
  8>public synchronized void ensureCapacity(int minimumCapacity)
   增加此向量的容量(如有必要),以确保其至少能够保存最小容量参数指定的组件数。
  9>public synchronized boolean equals(Object object)
   比较指定对象与此向量的相等性。当且仅当指定的对象也是一个 List、两个 List 大小相同,并且其中所有对应的元素对都相等 时才返回 true。
  10>public synchronized E firstElement()
   返回此向量的第一个组件 。
  11>public E get(int location)
   返回向量中指定位置的元素。
  12>public synchronized int hashCode()
   返回此向量的哈希码值。
  13>public int indexOf(Object object)
   返回此向量中第一次出现的指定元素的索引,如果此向量不包含该元素,则返回 -1。更确切地讲,返回满足 (o == null ? get(i) == null : o.equals(get(i))) 的最低索引 i;如果没有这样的索引,则返回 -1。
  14>public synchronized int indexOf(Object object, int location)
   返回此向量中第一次出现的指定元素的索引,从 index 处正向搜索,如果未找到该元素,则返回 -1。更确切地讲,返回满足 (i >= index && (o==null ? get(i) == null : o.equals(get(i)))) 的最低索引 i;如果没有这样的索引,则返回 -1 |
  15>public synchronized void insertElementAt(E object, int location)
   将指定对象作为此向量中的组件插入到指定的 index 处。
  16>public synchronized boolean isEmpty()
   测试此向量是否不包含组件。
  17>public synchronized E lastElement()
   返回此向量的最后一个组件。
  18>public synchronized int lastIndexOf(Object object)
   返回此向量中最后一次出现的指定元素的索引;如果此向量不包含该元素,则返回 -1。更确切地讲,返回满足 (o == null ? get(i)==null : o.equals(get(i))) 的最高索引 i;如果没有这样的索引,则返回 -1。
  19>public synchronized int lastIndexOf(Object object, int location)
   返回此向量中最后一次出现的指定元素的索引,从 index 处逆向搜索,如果未找到该元素,则返回 -1。更确切地讲,返回满足 (i <= index && (o == null ? get(i)==null : o.equals(get(i)))) 的最高索引 i;如果没有这样的索引,则返回 -1。
  20>public synchronized boolean retainAll(Collection<?> collection)
   在此向量中仅保留包含在指定 Collection 中的元素,即求交集。
  21>public synchronized E set(int location, E object)
   用指定的元素替换此向量中指定位置处的元素。
  22>public synchronized void setElementAt(E object, int location)
   将此向量指定 index 处的组件设置为指定的对象。
  23>public synchronized void setSize(int length)
   设置此向量的大小。如果新大小大于当前大小,则会在向量的末尾添加相应数量的 null 项。如果新大小小于当前大小,则丢弃索引 newSize 处及其之后的所有项。
  24>public synchronized int size()
   返回此向量中的组件数。
  25>public synchronized List subList(int start, int end)
   返回此 List 的部分视图,元素范围为从 start(包括)到 end(不包括)。
  26>public synchronized Object[ ] toArray()
   将Vector中元素以数组形式返回。
  27>public synchronized T[] toArray(T[] contents)
   返回一个数组,包含此向量中以恰当顺序存放的所有元素;返回数组的运行时类型为指定数组的类型。
  28>public synchronized String toString()
   返回此向量的字符串表示形式。
  29>public synchronized void trimToSize()
   对此向量的容量进行微调,使其等于向量的当前大小。

5.5 特殊方法

  除了线程安全以外,Vector的大部分功能实现与ArrayList并无太大区别,其中的一个较明显区别是:ArrayList默认扩容1.5倍,而Vector是2倍。
  1>public Vector(int capacity, int capacityIncrement)

    public Vector(int capacity, int capacityIncrement) {
        if (capacity < 0) {
            throw new IllegalArgumentException("capacity < 0: " + capacity);
        }
        elementData = newElementArray(capacity);
        elementCount = 0;
        this.capacityIncrement = capacityIncrement;
    }

   该方法是Vector的构造方法之一,其中capacity为初始容量,capacityIncrement为增长因子,如果该增长因子指定了,那么扩容的时候会每次新的数组大小会在原数组的大小基础上加上增长因子;如果不指定增长因子,那么就给原数组大小*2。

5.6 常用遍历方法

  Vector常用的遍历方法有4种:Iterator遍历、Enumeration遍历、普通for循环和foreach循环。
   1>Iterator遍历,示例代码如下:

		Iterator<String> it = vectorTest.iterator();
		while (it.hasNext()) {
			System.out.println(it.next());
		}

   2>Enumeration遍历,示例代码如下:

		Enumeration<String> enume = ((Vector<String>) vectorTest).elements();
        while(enume.hasMoreElements()){
            System.out.println(enume.nextElement().toString());
        }

   3>普通for循环遍历,示例代码如下:

		for (int i = 0; i < vectorTest.size(); i++) {
			System.out.println(vectorTest.get(i));	
		}

   4>foreach循环遍历,示例代码如下:

		for (String string : vectorTest) {
			System.out.println(string);
		}

六、Stack

  Stack继承Vector。Stack 类表示后进先出(LIFO)的对象堆栈。它通过五个操作对类 Vector 进行了扩展 ,允许将向量视为堆栈。它提供了通常的 push 和 pop 操作,以及取堆栈顶点的 peek 方法、测试堆栈是否为空的 empty 方法、在堆栈中查找项并确定到堆栈顶距离的 search 方法。
  Stack是线程安全的。

6.1 所有方法

  1>public Stack()
   创建一个空堆栈 。
  2>public boolean empty()
    测试堆栈是否为空 。
  3>public synchronized E peek()
   查看堆栈顶部的对象,但不从堆栈中移除它。
  4>public synchronized E pop()
   移除堆栈顶部的对象,并作为此函数的值返回该对象。
  5>public E push(E object)
   把项压入堆栈顶部 。
  6>public synchronized int search(Object o)
   返回对象在堆栈中的位置,以 1 为基数。

6.2 特殊方法

  1>public synchronized E peek()
   该方法的作用是:查看堆栈顶部的对象,但不从堆栈中移除它。
  2>public synchronized E pop()
   该方法的作用是:移除堆栈顶部的对象,并作为此函数的值返回该对象。
  3>public E push(E object)
   元素入栈。
  4>public synchronized int search(Object o)
   检索元素所在的位置,代码如下:

    public synchronized int search(Object o) {
        final Object[] dumpArray = elementData;
        final int size = elementCount;
        if (o != null) {
            for (int i = size - 1; i >= 0; i--) {
                if (o.equals(dumpArray[i])) {
                    return size - i;
                }
            }
        } else {
            for (int i = size - 1; i >= 0; i--) {
                if (dumpArray[i] == null) {
                    return size - i;
                }
            }
        }
        return -1;
    }

   该方法特殊的地方在于返回值,不是将i直接返回,而是返回的size - i。

6.3 常用遍历方法

  Stack常用的遍历方法有2种:栈弹出遍历和foreach循环遍历。
   1>栈弹出遍历,示例代码如下:

        while (!testStack.isEmpty()) {
             System.out.println(((Stack<String>) testStack).pop());
        }

   2>foreach循环遍历,示例代码如下:

        for (String str : testStack) {
                System.out.println(str);
        }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章