Java集合框架——List

前言

先上一个List集合下的一个简易的结构图:
在这里插入图片描述

1、ArrayList类

ArrayList的底层实现为数组,是List中最常用的类,查询效率高,删除、插入的操作效率较低;接下来看一下继承关系:

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable{.....}

下面对类中的成员变量及构造函数进行介绍:

	/**
     * Default initial capacity.
     * 默认的容量为10
     */
    private static final int DEFAULT_CAPACITY = 10;

    /**
     * 空的实例,容量为0
     */
    private static final Object[] EMPTY_ELEMENTDATA = {};

    /**
     * 默认大小的空实例,容量为10
     */
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

    /**
     * 存储数据数组
     */
    transient Object[] elementData; // non-private to simplify nested class access

    /**
     * The size of the ArrayList (the number of elements it contains).
     * ArrayList中包含的元素数量
     */
    private int size;

    /**
     * 设定容量的构造函数
     */
    public ArrayList(int initialCapacity) {
        if (initialCapacity > 0) {
            this.elementData = new Object[initialCapacity];
        } else if (initialCapacity == 0) {
            this.elementData = EMPTY_ELEMENTDATA;
        } else {
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }

    /**
     * Constructs an empty list with an initial capacity of ten.
     * 构建一个容量为10的空实例
     */
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

    /**
     * Constructs a list containing the elements of the specified
     * collection, in the order they are returned by the collection's
     * iterator.
     *
     * @param c the collection whose elements are to be placed into this list
     * @throws NullPointerException if the specified collection is null
     */
    public ArrayList(Collection<? extends E> c) {
    	// c=null,会抛出空指针异常
        elementData = c.toArray();
        if ((size = elementData.length) != 0) {
            // c.toArray might (incorrectly) not return Object[] (see 6260652)
            if (elementData.getClass() != Object[].class)
            	// 如果不为Object类型数组的转化为Object类型
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {
            // replace with empty array.
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }

添加数据:

	// 在数组尾部插入元素
    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }

	// 在特定的位置插入元素
    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++;
    }

	// 进行是否需要扩容的验证
    private void ensureCapacityInternal(int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }
		
        ensureExplicitCapacity(minCapacity);
    }

    private void ensureExplicitCapacity(int minCapacity) {
        modCount++;

        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
        	// 如果插入元素以后元素的个数大于数组的容量,则进行扩容
            grow(minCapacity);
    }

扩容操作:

    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        // 新的容量为原来的容量+原来容量的0.5倍
        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在进行查询效率较高
  • 在进行插入时如果为顺序插入,则直接插入到最后,也很高效,但是如果插入到中间,由于会涉及到其后的数据向后移位的操作,所以会稍慢;如果是删除操作,删除中间的数据时,其后的数据需要向前移位所以会稍慢一些
  • ArrayList是线程不安全
  • ArrayList是有序的
  • ArrayList允许值为null,可以有重复值
2、Vector类

Vector类的底层实现与ArrayList的底层是一样的,这两者最主要的区别是Vector是线程安全的,我们可以看下Vector的源码:

	// 添加数据
    public synchronized boolean add(E e) {
        modCount++;
        ensureCapacityHelper(elementCount + 1);
        elementData[elementCount++] = e;
        return true;
    }
    // 移除数据
    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;
    }
....

Vector之所以线程安全是因为,在其方法上添加了synchronized 关键字;接下来看一下Vector的扩容方式:

    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        // 如果capacityIncrement(扩容增量)<=0,则扩容时容量提升一倍
        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);
    }

小结:

  • Vector是线程安全的,因为方法中含有synchronized 关键字
  • Vector可以自己设置扩容增量,默认为0,当扩容增量<=0时,则扩容时容量提升为原来的一倍
  • Vector允许值为null,可以有重复值
3、LinkedList类

我们直接来看LinkedList源码:

public class LinkedList<E>
    extends AbstractSequentialList<E>
    implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{
	// 数据量大小
	 transient int size = 0;

    /**
     * Pointer to first node.
     * Invariant: (first == null && last == null) ||
     *            (first.prev == null && first.item != null)
     * 链表的头节点
     */
    transient Node<E> first;

    /**
     * Pointer to last node.
     * Invariant: (first == null && last == null) ||
     *            (last.next == null && last.item != null)
     * 链表的尾节点
     */
    transient Node<E> last;

	 /**
     * 无参构造函数
     */
    public LinkedList() {
    }

    /**
     * Constructs a list containing the elements of the specified
     * collection, in the order they are returned by the collection's
     * iterator.
     *
     * @param  c the collection whose elements are to be placed into this list
     * @throws NullPointerException if the specified collection is null
     */
    public LinkedList(Collection<? extends E> c) {
        this();
        addAll(c);
    }
}

来看一下LinkedList每一个节点上的具体数据结构:

    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;
        }
    }

看到这里是不是很清楚的就能知道,LinkedList的底层结构为一个双向链表,关于双向链表就不用多说了吧。

小结:

  • 由于底层是链表的结构,所以LinkedList增、删的操作相对效率更高一些,查询的效率较低
  • LinkedList是有序的
  • LinkedList线程不安全
  • LinkedList允许值为null,可以有重复值
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值