java容器—Collection(ArrayList)

java容器

ArrayList
概述

基于动态数组实现,支持随机访问,实现了List接口,顺序容器(元素存放的数据与放心去的顺序相同,允许放入null元素,底层通过数组实现)

每个ArrayList都有一个容量(capacity),表示底层数组的实际大小,容器内存储元素的个数不能多余当前容量。添加元素时,若容量不足时,自动扩容。这里的数组是一个Object数组,以便能够容纳任何类型的对象

ps: ArrayList没有实现同步,如果需要多个线程并发访问用户可以手动同步,也可使用Vector替代

底层数据结构
//transient 不需要序列化的属性
transient Object[] elementData; // non-private to simplify nested class access

    /**
     * The size of the ArrayList (the number of elements it contains).
     *
     */
    private int size;
构造函数
private static final Object[] EMPTY_ELEMENTDATA = {};
private static final int DEFAULT_CAPACITY = 10;
//构造一个固定容量到小的arrayList
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);
        }
    }

    //默认数组大小为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) {
        elementData = c.toArray();
        if ((size = elementData.length) != 0) {
            //如果数组缓冲区的类型不是Object[]的,要用Arrays.copyOf()方法转化为Object[],例如new ArrayList 和 Arrays.asList()在toArray()后返回的类型不同,后者返回java.util.Arrays&ArrayList,toArray()后返回类java.lang.String
            if (elementData.getClass() != Object[].class)
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {
            // 否则返回空链表
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }
添加元素 add(), addAll()
  • Add(e) 和add(index ,e)这两个方法都是向容器中添加新元素

    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 rangeCheckForAdd(int index) {
            if (index > size || index < 0)
                throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
        }
    
  • addAll()

    //在末尾添加
    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;
        }
    
    //指定位置添加
        public boolean addAll(int index, Collection<? extends E> c) {
            rangeCheckForAdd(index);
    
            Object[] a = c.toArray();
            int numNew = a.length;
          //手动扩容
            ensureCapacityInternal(size + numNew);  // Increments modCount
    			
            int numMoved = size - index;
            if (numMoved > 0)
                System.arraycopy(elementData, index, elementData, index + numNew,
                                 numMoved);
    
            System.arraycopy(a, 0, elementData, index, numNew);
            size += numNew;
            return numNew != 0;
        }
    //时间复杂度不仅跟插入元素的多少有关,也跟插入的位置有关
    
修改元素 Set()
//直接对数组指定的位置赋值
public E set(int index, E element) {
  //校验数组下标是否越界
        rangeCheck(index);

        E oldValue = elementData(index);
  //赋值到指定的位置,复制的仅仅是引用
        elementData[index] = element;
        return oldValue;
    }
 E elementData(int index) {
        return (E) elementData[index];
    }
获取元素Get()
 public E get(int index) {
        rangeCheck(index);
		//注意类型转换
        return elementData(index);
    }
 E elementData(int index) {
        return (E) elementData[index];
    }

//获取元素第一次出现的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;
    }

//获取元素最后一次出现的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;
    }
删除元素 remove()
//删除指定位置的元素,将需要删除点之后的元素向前移动一个位置
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);
  //清除该位置的引用,让GC起作用
        elementData[--size] = null; // clear to let GC do its work

        return oldValue;
    }
//ps:对象能否被GC的依据是是否还有引用指向它,否则原来的对象就一直不会回收
自动扩容
  • 添加元素时可能会导致容量不足,在添加元素之前,都要检查添加元素后是否会超出数组长度,如果需要则自动扩容,最终通过grow()方法完成
//数组扩容,在实际添加大量元素前,也可使用此方法来手动增加ArrayList实例的容量,以减少递增式再分配的数量
public void ensureCapacity(int minCapacity) {
        int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
            // any size if not default element table
            ? 0
            // larger than default for default empty table. It's already
            // supposed to be at default size.
            : DEFAULT_CAPACITY;

        if (minCapacity > minExpand) {
            ensureExplicitCapacity(minCapacity);
        }
    }

    private void ensureCapacityInternal(int minCapacity) {
        ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
    }
	private static int calculateCapacity(Object[] elementData, int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            return Math.max(DEFAULT_CAPACITY, minCapacity);
        }
        return minCapacity;
    }

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

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

    /**
     * The maximum size of array to allocate.
     * Some VMs reserve some header words in an array.
     * Attempts to allocate larger arrays may result in
     * OutOfMemoryError: Requested array size exceeds VM limit
     */
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

   //数组扩容时,将老数组中的元素拷贝一份到新数组中,每次数组容量的增长大约是原容量的1.5倍
    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);
    }
private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }
调整容量
//将底层数组的容量调整为当前列表保存的实际元素的大小
    public void trimToSize() {
        modCount++;
        if (size < elementData.length) {
            elementData = (size == 0)
              ? EMPTY_ELEMENTDATA
              : Arrays.copyOf(elementData, size);
        }
    }
Fail-Fast机制

采用了快速失败的机制,通过记录modCount参数来实现。在面对并发的修改时,迭代器很快就会完全失败,而不是冒着在将来某个不确定时间发生任意不确定行为的风险。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值