java集合详解

java中集合大概可以分为两大类,Collection和map。而collection又分别包括set和list,今天我们探讨一下继承自collection集合的set和list的相关内容和效率比较;

 

Collection:一个独立元素的序列,这些元素按照一条或者多条规则。list必须按照插入的顺序保存元素,而set不能有重复元素。queue按照排队规格来确定对象产生的顺序(通常和他被插入的顺序相同,先进先出)

  • 集合中概括了序列的概念---用于存放一组对象的方式。所以说集合中的元素必须为对象类型(即继承了Object的对象类型)
  • 如何向集合中添加一组元素呢?大概可以分为以下几种方法:
  1. Collections.addAll()方法,它可以接收一个Collection对象作为参数,把对应的元素加入到现有集合中。但是要注意的是所加入数组元素的类型必须和集合所定义的元素类型一致
  2. 构造器方法。Collection集合可以接受一个Collection元素作为构造器参数,构造的新集合中包含有参数集合的元素
  3. Arrays.asList方法,返回的是一个list类型的集合

 

public static <T> List<T> asList(T... a) {
        return new ArrayList<>(a);
    }

 但是注意的是,这种方法返回的list底层实现是个数组,所以大小是固定的不能改变。使用add或者delete方法可能会运行报错。

public static void main(String[] args) {
        List<Integer> testList = Arrays.asList(1, 2, 3);
        testList.add(1);
        for (Integer id : testList) {
            System.out.println(id);
        }
    }


Exception in thread "main" java.lang.UnsupportedOperationException

 所以这个方法我们一般都与addAll或者构造器方法连用,如下

List<Integer> testList = new ArrayList<>();
        testList.addAll(Arrays.asList(1, 2, 3));
        testList.add(1);

或者

List<Integer> testList = new ArrayList<>(Arrays.asList(1, 2, 3));
        testList.add(1);

 

list一般可以分为一下三类

  • ArrayList
  • LinkedList
  • Vector

首先我们先大概了解一下这三类集合和他们的区别和联系

一、ArrayList也是我们开发中用到最多的集合,他是一种动态数组,并且以特定的顺序保存数组中的元素,数组大小不是固定的,而是可以随时改变,动态分配数据空间的数组。ArrayList实现了list接口,而list接口继承自Collection集合

 

日常开发中通常使用如下的方式实现向上转型,以便于接口的通用性

List<Integer> List = new ArrayList<>();

但是当我们需要用特定的类中的方法的时候,就只能创建具体的对象,否则将不能使用具体类中的特定方法。

关于ArrayList的效率,因为ArrayList采用的是随机访问元素的策略,所以说对于数组的遍历是效率比较高的,但是特定位置插入或者删除的话,由于随机访问策略,每个插入/删除元素之后的元素都需要变动位置,所以效率比较低。

 

 二、LinkedList同样实现了List接口。与ArrayList不同的是,LinkedList的实现方式是基于链表的非随机存储策略。所以在效率方面,对于数组的遍历是不如ArrayList的,但是在特定位置的插入和删除是优于list的

接下来看一下Linklist的一些重要方法

linkedList的继承方式的大概如下:

Collection-----AbstractCollection-----AbstractList--------AbstractSequentialList--------LinkedList

除此之外,LInkedList还实现了如下接口

public class LinkedList<E>
    extends AbstractSequentialList<E>
    implements List<E>, Deque<E>, Cloneable, java.io.Serializable

注:deque容器为一个给定类型的元素进行线性处理,像向量一样,它能够快速地随机访问任一个元素,并且能够高效地插入和删除容器的尾部元素。但它又与vector不同,deque支持高效插入和删除容器的头部元素,因此也叫做双端队列

 Node<E>是链表元素的存储方式,以节点的方式存储;每个节点包括item(对象元素类型),next和pre节点

private static class Node<E> {
        E item;
        Node<E> next;
        Node<E> prev;

        Node(Node<E> prev, E element, Node<E> next) {
            this.item = element;
            this.next = next;
            this.prev = prev;
        }
    }

首先是一些普通的方法

  • add();可以看出add方法是加入了一个元素之后,直接调用LinkLast()方法,即当前节点作为链表的尾部元素。如果是空的链表,加入的元素将变成头部元素
public boolean add(E e) {
        linkLast(e);
        return true;
    }

void linkLast(E e) {
        final Node<E> l = last;
        final Node<E> newNode = new Node<>(l, e, null);
        last = newNode;
        if (l == null)
            first = newNode;
        else
            l.next = newNode;
        size++;
        modCount++;
    }
  • remove()方法;remove方法根据传入的元素是否为空分为两种情况。如果为空的话,找到元素为空的节点,否则找到元素为传入参数对象的节点。注意此时的判断方法是equal,因为对象的==只是判断引用地址的相同。同样unlinked的方法通过传入的节点判断其前后节点。如果pre为空或者next为空说明是头尾节点,直接把起前后节点作为新的头尾节点即可。否则需要断开前后连接,把前节点的next节点置为当前节点的next节点,next节点的pre节点置为当前节点的pre节点,并且把当前节点的元素置为空即可
public boolean remove(Object o) {
        if (o == null) {
            for (Node<E> x = first; x != null; x = x.next) {
                if (x.item == null) {
                    unlink(x);
                    return true;
                }
            }
        } else {
            for (Node<E> x = first; x != null; x = x.next) {
                if (o.equals(x.item)) {
                    unlink(x);
                    return true;
                }
            }
        }
        return false;
    }


//unlinked方法----Unlinks non-null node x

E unlink(Node<E> x) {
        // assert x != null;
        final E element = x.item;
        final Node<E> next = x.next;
        final Node<E> prev = x.prev;

        if (prev == null) {
            first = next;
        } else {
            prev.next = next;
            x.prev = null;
        }

        if (next == null) {
            last = prev;
        } else {
            next.prev = prev;
            x.next = null;
        }

        x.item = null;
        size--;
        modCount++;
        return element;
    }
  • getFirst()和getLast()获取首/尾节点:需要注意的是如果首/尾节点是空的话,即list是空将报错--NoSuchElementException
public E getFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return f.item;
    }

public E getLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return l.item;
    }
  • removeFirst(),removeLast()移除首尾节点---同样要求数组不能为空,否则报错
public E removeFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return unlinkFirst(f);
    }


public E removeLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return unlinkLast(l);
    }
  •  addFirst(E e),addLast(E e)添加首尾节点,置顶元素从头或者尾加入;实现原理是如果list为空的话,当前节点直接置为首节点,否则首/尾节点作为当前节点的next/pre节点
public void addFirst(E e) {
        linkFirst(e);
    }

 private void linkFirst(E e) {
        final Node<E> f = first;
        final Node<E> newNode = new Node<>(null, e, f);
        first = newNode;
        if (f == null)
            last = newNode;
        else
            f.prev = newNode;
        size++;
        modCount++;
    }

public void addLast(E e) {
        linkLast(e);
    }

void linkLast(E e) {
        final Node<E> l = last;
        final Node<E> newNode = new Node<>(l, e, null);
        last = newNode;
        if (l == null)
            first = newNode;
        else
            l.next = newNode;
        size++;
        modCount++;
    }
  • contain(E e)方法---确定是否包含某个元素,实际是通过元素的位置判断的
public boolean contains(Object o) {
        return indexOf(o) != -1;
    }

public int indexOf(Object o) {
        int index = 0;
        if (o == null) {
            for (Node<E> x = first; x != null; x = x.next) {
                if (x.item == null)
                    return index;
                index++;
            }
        } else {
            for (Node<E> x = first; x != null; x = x.next) {
                if (o.equals(x.item))
                    return index;
                index++;
            }
        }
        return -1;
    }
  • addAll()批量就加入----根据当前linkedList的size和传入的集合进行添加,循环前先获取前置节点。循环时将前节点的下个节点置为新节点,再把当前节点作为前节点继续循环
public boolean addAll(Collection<? extends E> c) {
        return addAll(size, c);
    }

public boolean addAll(int index, Collection<? extends E> c) {
        checkPositionIndex(index);

        Object[] a = c.toArray();
        int numNew = a.length;
        if (numNew == 0)
            return false;

        Node<E> pred, succ;
        if (index == size) {
            succ = null;
            pred = last;
        } else {
            succ = node(index);
            pred = succ.prev;
        }

        for (Object o : a) {
            @SuppressWarnings("unchecked") E e = (E) o;
            Node<E> newNode = new Node<>(pred, e, null);
            if (pred == null)
                first = newNode;
            else
                pred.next = newNode;
            pred = newNode;
        }

        if (succ == null) {
            last = pred;
        } else {
            pred.next = succ;
            succ.prev = pred;
        }

        size += numNew;
        modCount++;
        return true;
    }

 

三、Vector介绍

  • Vector 是矢量队列,它是JDK1.0版本添加的类。继承于AbstractList,实现了List, RandomAccess, Cloneable这些接口.

 

  • Vector 继承了AbstractList,实现了List;所以,它是一个队列,支持相关的添加、删除、修改、遍历等功能
  • Vector 实现了RandmoAccess接口,即提供了随机访问功能。RandmoAccess是java中用来被List实现,为List提供快速访问功能的。在Vector中,我们即可以通过元素的序号快速获取元素对象;这就是快速随机访问。

 

  • Vector 实现了Cloneable接口,即实现clone()函数。它能被克隆。

我们研究下Vector的四种构造方法

//不传参数默认容量为10
public Vector() {
        this(10);
    }


//不传每次扩容的大小  默认扩容方式为翻倍增加
public Vector(int initialCapacity) {
        this(initialCapacity, 0);
    }


//initialCapacity指的是初始容量,而capacityIncrement指的是容量的增加值
public Vector(int initialCapacity, int capacityIncrement) {
        super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        this.elementData = new Object[initialCapacity];
        this.capacityIncrement = capacityIncrement;
    }

//通过Coolection集合直接生成Vector;elementCount指的是元素的数量
public Vector(Collection<? extends E> c) {
        elementData = c.toArray();
        elementCount = elementData.length;
        // c.toArray might (incorrectly) not return Object[] (see 6260652)
        if (elementData.getClass() != Object[].class)
            elementData = Arrays.copyOf(elementData, elementCount, Object[].class);
    }

四种构造方法中,都是通过定义或者默认值来定义主要的三个参数

protected Object[] elementData;//对象数组,用于存储数值
protected int elementCount;//对象个数,类似于length。注意这个不是vector的容量,是里面包含元素的数量。代表容量的是elementData的长度
protected int capacityIncrement;扩容的倍数,源码中如下定义的:
* The amount by which the capacity of the vector is automatically
* incremented when its size becomes greater than its capacity.  If
* the capacity increment is less than or equal to zero, the capacity
* of the vector is doubled each time it needs to grow.

如果说这个值小于等于0,则每次扩容都是翻倍

 vector的插入有以下几种方法

//不指定位置插入--插入方法是用同步关键字修饰,所以说是线程安全的
//方法中的modCount指的是vector被修改的次数
public synchronized boolean add(E e) {
    modCount++;
    ensureCapacityHelper(elementCount + 1);
    elementData[elementCount++] = e;
    return true;
}
private void ensureCapacityHelper(int minCapacity) {
    // overflow-conscious code
    if (minCapacity - elementData.length > 0)
        grow(minCapacity);
}

 //grow方法是扩容的具体实现

private void grow(int minCapacity) {
    // overflow-conscious code
    int oldCapacity = elementData.length;
//如果定义的容量增长大于零则加上容量增长量,否则直接翻倍
    int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
                                     capacityIncrement : oldCapacity);
//看翻倍后的容量与当前容量的比较,如果小于当前容量,则新的容量为当前容量
    if (newCapacity - minCapacity < 0)
        newCapacity = minCapacity;
//如果扩容后大于Array的容量限制,返回的是Integer的最大值
    if (newCapacity - MAX_ARRAY_SIZE > 0)
        newCapacity = hugeCapacity(minCapacity);
    elementData = Arrays.copyOf(elementData, newCapacity);
}
private static int hugeCapacity(int minCapacity) {
    if (minCapacity < 0) // overflow
        throw new OutOfMemoryError();
    return (minCapacity > MAX_ARRAY_SIZE) ?
        Integer.MAX_VALUE :
        MAX_ARRAY_SIZE;
}

数组最大的容量为Integer的最大值减8

private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

 //指定位置的插入

public void add(int index, E element) {
    insertElementAt(element, index);
}

//插入方法使用同步关键字修饰,所以说同样是线程安全的 

public synchronized void insertElementAt(E obj, int index) {
    modCount++;
    if (index > elementCount) {
        throw new ArrayIndexOutOfBoundsException(index
                                                 + " > " + elementCount);
    }
    ensureCapacityHelper(elementCount + 1);
    System.arraycopy(elementData, index, elementData, index + 1, elementCount - index);
    elementData[index] = obj;
    elementCount++;
}
* @param      src      the source array.
* @param      srcPos   starting position in the source array.
* @param      dest     the destination array.
* @param      destPos  starting position in the destination data.
* @param      length   the number of array elements to be copied.
* @exception  IndexOutOfBoundsException  if copying would cause
*               access of data outside array bounds.
* @exception  ArrayStoreException  if an element in the <code>src</code>
*               array could not be stored into the <code>dest</code> array
*               because of a type mismatch.
* @exception  NullPointerException if either <code>src</code> or
*               <code>dest</code> is <code>null</code>.
public static native void arraycopy(Object src,  int  srcPos,
                                    Object dest, int destPos,
                                    int length);

实现方法大概是:先进行越界判断-----再次进行扩容(由于指定位置,所以通过当前元素数量加一来判断是否需要扩容)-------调用System.arraycopy方法,这个方法是把index之后的所有内容通过复制的方法向后面移动一位----再改变当前index位置的值,实现了插入到现在的位置

Vector的移除有一下几种方法

public boolean remove(Object o) {
    return removeElement(o);
}

//根据对象来移除---首先获取对象所在的位置 

public synchronized boolean removeElement(Object obj) {
    modCount++;
    int i = indexOf(obj);
    if (i >= 0) {
        removeElementAt(i);
        return true;
    }
    return false;
}

//把index后面的向前复制一位(所有元素全部前移一位)---然后最后一位置为空 

public synchronized void removeElementAt(int index) {
    modCount++;
    if (index >= elementCount) {
        throw new ArrayIndexOutOfBoundsException(index + " >= " +
                                                 elementCount);
    }
    else if (index < 0) {
        throw new ArrayIndexOutOfBoundsException(index);
    }
    int j = elementCount - index - 1;
    if (j > 0) {
        System.arraycopy(elementData, index + 1, elementData, index, j);
    }
    elementCount--;
    elementData[elementCount] = null; /* to let gc do its work */
}
public int indexOf(Object o) {
    return indexOf(o, 0);
}
public synchronized int indexOf(Object o, int index) {
    if (o == null) {
        for (int i = index ; i < elementCount ; i++)
            if (elementData[i]==null)
                return i;
    } else {
        for (int i = index ; i < elementCount ; i++)
            if (o.equals(elementData[i]))
                return i;
    }
    return -1;
}

//全部移除元素 

public synchronized void removeAllElements() {
    modCount++;
    // Let gc do its work
    for (int i = 0; i < elementCount; i++)
        elementData[i] = null;

    elementCount = 0;
}

 //移除指定位置元素并且返回元素的值

public synchronized E remove(int index) {
    modCount++;
    if (index >= elementCount)
        throw new ArrayIndexOutOfBoundsException(index);
    E oldValue = elementData(index);

    int numMoved = elementCount - index - 1;
    if (numMoved > 0)
        System.arraycopy(elementData, index+1, elementData, index,
                         numMoved);
    elementData[--elementCount] = null; // Let gc do its work

    return oldValue;
}

 //继承自父类的方法,移除置顶集合中的元素

public synchronized boolean removeAll(Collection<?> c) {
    return super.removeAll(c);
}
public boolean removeAll(Collection<?> c) {
    Objects.requireNonNull(c);
    boolean modified = false;
    Iterator<?> it = iterator();
    while (it.hasNext()) {
        if (c.contains(it.next())) {
            it.remove();
            modified = true;
        }
    }
    return modified;
}

 

 //移除置顶范围内的元素

protected synchronized void removeRange(int fromIndex, int toIndex) {
    modCount++;
    int numMoved = elementCount - toIndex;
    System.arraycopy(elementData, toIndex, elementData, fromIndex,
                     numMoved);

    // Let gc do its work
    int newElementCount = elementCount - (toIndex-fromIndex);
    while (elementCount != newElementCount)
        elementData[--elementCount] = null;
}

 

 

四、关于ArrayList和Vector的扩容机制的比较探讨

ArrayList的扩容:

//size代表arrayList的容量

private int size;
public boolean add(E e) {
    ensureCapacityInternal(size + 1);  // Increments modCount!!
    elementData[size++] = e;
    return true;
}
private void ensureCapacityInternal(int minCapacity) {
    ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}

//首先根据需要的容量大小和当前的数组计算扩充后的容量大小。如果当前的存储元素的数组为空,则返回默认空间和需要扩容的较大值(默认空间大小为10)。否则直接返回扩容后的空间大小

private static int calculateCapacity(Object[] elementData, int minCapacity) {
    if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
        return Math.max(DEFAULT_CAPACITY, minCapacity);
    }
    return minCapacity;
}
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
private static final int DEFAULT_CAPACITY = 10;
//增加修改的次数如果需要增长的空间大于当前数组的长度,调用grow方法
private void ensureExplicitCapacity(int minCapacity) {
    modCount++;

    // overflow-conscious code
    if (minCapacity - elementData.length > 0)
        grow(minCapacity);
}

新的容量为原来的容量+原来的容量*50%(oldCapacity + (oldCapacity >> 1))。如果扩容后还是小于需要的容量,则把需要的容量作为新的容量

private void grow(int minCapacity) {
    // overflow-conscious code
    int oldCapacity = elementData.length;
    int newCapacity = oldCapacity + (oldCapacity >> 1);
    if (newCapacity - minCapacity < 0)
        newCapacity = minCapacity;
    if (newCapacity - MAX_ARRAY_SIZE > 0)
        newCapacity = hugeCapacity(minCapacity);
    // minCapacity is usually close to size, so this is a win:
    elementData = Arrays.copyOf(elementData, newCapacity);
}

总结一下:ArrayList是通过数组实现的,但是数组的长度是固定的。所以每次添加元素的时候,如果添加后的容量大于内部数组的容量就需要进行扩容操作。扩容机制是在当前的基础上增加50%,所以容量一般如下:10,15,22,33....等。但是如果需要的容量还是大于扩容后的容量的话,则以需要的容量作为数组的容量。最后把原来数组的元素根据新的容量进行copy

 而Vector的数组的扩容的区别就在于扩容机制,如果定义了增长值的话,扩容时会按照增长值增长,否则会翻倍增长

private void grow(int minCapacity) {
    // overflow-conscious code
    int oldCapacity = elementData.length;
    int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
                                     capacityIncrement : oldCapacity);
    if (newCapacity - minCapacity < 0)
        newCapacity = minCapacity;
    if (newCapacity - MAX_ARRAY_SIZE > 0)
        newCapacity = hugeCapacity(minCapacity);
    elementData = Arrays.copyOf(elementData, newCapacity);
}

 

五,关于三种集合线程安全的比较

  • ArrayList不是线程安全的,比较适合用在单线程情况下
  • LinkedList不是线程安全的
  • Vector由于其方法含有关键字synchronized ,所以是线程安全的,但线程安全同样决定了其效率不高

 

原因如下:

比如当添加一个元素的时候,获取size,扩容,给元素赋值并不是同时完成的,而是分步骤的。如果说A元素加入的时候获取了size,保存了元素,但是没有增加size,这时候B进行操作获取的size还是未增加前的size。这样是不安全的

六,关于集中数组的插入,移除和遍历的效率比较

插入的效率如下:

 一.直接插入-我们以插入10000000个数字为例

public static void main(String[] args) {
    long startTime;
    long endTime;
    startTime = System.currentTimeMillis();
    ArrayList list = new ArrayList();
    for (int i = 0; i < 10000000; i++) {
        list.add(1);
    }
    endTime = System.currentTimeMillis();
    long interval = endTime - startTime;
    System.out.println("time:" + interval + " ms");

}

time:153 ms

public static void main(String[] args) {
    long startTime;
    long endTime;
    startTime = System.currentTimeMillis();
    LinkedList list1 = new LinkedList();
    for (int i = 0; i < 10000000; i++) {
        list1.add(1);
    }
    endTime = System.currentTimeMillis();
    long interval = endTime - startTime;
    System.out.println("time:" + interval + " ms");

}

time:3542 ms

public static void main(String[] args) {
    long startTime;
    long endTime;
    startTime = System.currentTimeMillis();
    Vector list = new Vector();
    for (int i = 0; i < 10000000; i++) {
        list.add(1);
    }
    endTime = System.currentTimeMillis();
    long interval = endTime - startTime;
    System.out.println("time:" + interval + " ms");

}

time:285 ms

可以看出,直接在列表后面插入的话效率arrayList>vector>LinkedList

在指定位置插入,ArrayList和Vector由于每次插入都要移动大量数据,效率可能相当低。所以这次我们以100000次操作为例:

public static void main(String[] args) {
    long startTime;
    long endTime;
    startTime = System.currentTimeMillis();
    ArrayList list = new ArrayList();
    for (int i = 0; i < 100000; i++) {
        list.add(0,1);
    }
    endTime = System.currentTimeMillis();
    long interval = endTime - startTime;
    System.out.println("time:" + interval + " ms");

}

time:1080 ms

public static void main(String[] args) {
    long startTime;
    long endTime;
    startTime = System.currentTimeMillis();
    LinkedList list = new LinkedList();
    for (int i = 0; i < 100000; i++) {
        list.add(0,1);
    }
    endTime = System.currentTimeMillis();
    long interval = endTime - startTime;
    System.out.println("time:" + interval + " ms");

}

time:10 ms

public static void main(String[] args) {
    long startTime;
    long endTime;
    startTime = System.currentTimeMillis();
    Vector list = new Vector();
    for (int i = 0; i < 100000; i++) {
        list.add(0,1);
    }
    endTime = System.currentTimeMillis();
    long interval = endTime - startTime;
    System.out.println("time:" + interval + " ms");

}

time:1064 ms

 

在效率上不出所料 LinkedList>Vector=ArrayList

在遍历这方面的表现呢?

public static void main(String[] args) {
    long startTime;
    long endTime;
    startTime = System.currentTimeMillis();
    ArrayList list = new ArrayList();
    for (int i = 0; i < 100000; i++) {
        list.add(0,1);
    }
    startTime = System.currentTimeMillis();
    for (int i = 0; i < 100000; i++) {
        Integer a=(Integer)list.get(i);
    }
    endTime = System.currentTimeMillis();
    long interval = endTime - startTime;
    System.out.println("time:" + interval + " ms");

}

time:2 ms

public static void main(String[] args) {
    long startTime;
    long endTime;
    startTime = System.currentTimeMillis();
    LinkedList list = new LinkedList();
    for (int i = 0; i < 100000; i++) {
        list.add(0,1);
    }
    startTime = System.currentTimeMillis();
    for (int i = 0; i < 100000; i++) {
        Integer a=(Integer)list.get(i);
    }
    endTime = System.currentTimeMillis();
    long interval = endTime - startTime;
    System.out.println("time:" + interval + " ms");

}

time:4159 ms

public static void main(String[] args) {
    long startTime;
    long endTime;
    startTime = System.currentTimeMillis();
    Vector list = new Vector();
    for (int i = 0; i < 100000; i++) {
        list.add(0,1);
    }
    startTime = System.currentTimeMillis();
    for (int i = 0; i < 100000; i++) {
        Integer a=(Integer)list.get(i);
    }
    endTime = System.currentTimeMillis();
    long interval = endTime - startTime;
    System.out.println("time:" + interval + " ms");

}

time:3 ms

 

 

 在遍历方面 LinkedList的表现特别差

最后remove

public static void main(String[] args) {
    long startTime;
    long endTime;
    startTime = System.currentTimeMillis();
    ArrayList list = new ArrayList();
    for (int i = 0; i < 100000; i++) {
        list.add(0,1);
    }
    startTime = System.currentTimeMillis();
    for (int i = 0; i < 100000; i++) {
        list.remove(0);
    }
    endTime = System.currentTimeMillis();
    long interval = endTime - startTime;
    System.out.println("time:" + interval + " ms");

}

time:1048 ms

public static void main(String[] args) {
    long startTime;
    long endTime;
    startTime = System.currentTimeMillis();
    LinkedList list = new LinkedList();
    for (int i = 0; i < 100000; i++) {
        list.add(0,1);
    }
    startTime = System.currentTimeMillis();
    for (int i = 0; i < 100000; i++) {
        list.remove(0);
    }
    endTime = System.currentTimeMillis();
    long interval = endTime - startTime;
    System.out.println("time:" + interval + " ms");

}

time:3 ms

public static void main(String[] args) {
    long startTime;
    long endTime;
    startTime = System.currentTimeMillis();
    Vector list = new Vector();
    for (int i = 0; i < 100000; i++) {
        list.add(0,1);
    }
    startTime = System.currentTimeMillis();
    for (int i = 0; i < 100000; i++) {
        list.remove(0);
    }
    endTime = System.currentTimeMillis();
    long interval = endTime - startTime;
    System.out.println("time:" + interval + " ms");

}

time:986 ms

 总结一下,在遍历和按顺序的插入元素时,ArrayList和Vector以随机访问的优势性能完爆LinkedList;但是在指定位置插入和删除时,LinkedList以其链表结构大胜其他两个。而ArrayList和Vector在其他方面相差无几,但是Vector是线程安全的,所以效率略低于ArrayList。在单线程环境,建议使用ArrayList。在需求多线程线程安全的条件下,建议使用Vector。而在插入和删除操作比较多的情况下,LinkedList是更好的选择

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值