ArrayList简介(arraylist方法有哪些)
简介
ArrayList是Java集合框架中比较常用的数据结构,继承自AbstractList,实现了List接口,底层基于数组实现容量大小动态变化,允许null成员,同时还实现了RandomAccess、Cloneable、Serializable接口,所有ArrayList是支持快速访问、复制、序列化的。
成员变量
ArrayList底层是基于数组来实现容量动态变化的。
/** * The size of the ArrayList (the number of elements it contains). */ private int size; // 实际元素个数 transient Object[] elementData; 复制代码
注:size表示数组中实际的元素个数,elementData.length表示可容纳多少个元素(容量),
默认初始容量为10,
/** * Default initial capacity. */ private static final int DEFAULT_CAPACITY = 10;复制代码
modCount定义在AbstractList中,记录对List操作的次数
protected transient int modCount = 0;复制代码
下面两个变量是用在构造函数里面的
/** * Shared empty array instance used for empty instances. */ private static final Object[] EMPTY_ELEMENTDATA = {}; /** * Shared empty array instance used for default sized empty instances. We * distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when * first element is added. */ private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};复制代码
两个空的数组有什么区别呢? We distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when first element is added. 简单来讲就是第一次添加元素时知道该 elementData 从空的构造函数还是有参构造函数被初始化的。以便确认如何扩容。
构造函数
无参构造函数
/** * Constructs an empty list with an initial capacity of ten. */ public ArrayList() { this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; }复制代码
注:构造一个初始容量为10的List集合,构造函数给elementData赋值了一个空的数组,在第一次添加元素时容量扩大至10
构造一个初始容量大小为initialCapacity的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); } }复制代码
使用collection来构造ArrayList函数
public ArrayList(Collection<? extends E> c) { elementData = c.toArray(); if ((size = elementData.length) != 0) { // c.toArray might (incorrectly) not return Object[] (see 6260652) if (elementData.getClass() != Object[].class) elementData = Arrays.copyOf(elementData, size, Object[].class); } else { // replace with empty array. this.elementData = EMPTY_ELEMENTDATA; } }复制代码
将collection转化为数组,并赋值给elementData
主要操作方法解析
Add操作
public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true; } 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; int newCapacity = oldCapacity + (oldCapacity >> 1);//1.5倍 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); } 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++; } 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; }复制代码
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); elementData[--size] = null; // clear to let GC do its work return oldValue; } 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 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 }复制代码
Get操作
public E get(int index) { rangeCheck(index); return elementData(index); }复制代码
迭代器Iterator
集合中,for循环遍历的时候不可对集合进行remove操作,因为remove会改变集合的大小,从而造成结果不准确或数组越界
public Iterator<E> iterator() { return new Itr(); } private class Itr implements Iterator<E> { int cursor; // index of next element to return int lastRet = -1; // index of last element returned; -1 if no such int expectedModCount = modCount; // prevent creating a synthetic constructor Itr() {} public boolean hasNext() { return cursor != size; } @SuppressWarnings("unchecked") public E next() { checkForComodification(); int i = cursor; if (i >= size) throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) throw new ConcurrentModificationException(); cursor = i + 1; return (E) elementData[lastRet = i]; } public void remove() { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { ArrayList.this.remove(lastRet); cursor = lastRet; lastRet = -1; expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } @Override public void forEachRemaining(Consumer<? super E> action) { Objects.requireNonNull(action); final int size = ArrayList.this.size; int i = cursor; if (i < size) { final Object[] es = elementData; if (i >= es.length) throw new ConcurrentModificationException(); for (; i < size && modCount == expectedModCount; i++) action.accept(elementAt(es, i)); // update once at end to reduce heap write traffic cursor = i; lastRet = i - 1; checkForComodification(); } } final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } }复制代码
成员变量:
cursor:代表下一个要访问的元素下标
lastRet:代表上一个要访问的元素下标
expectedModCount:代表对ArrayList修改次数的期望值,初始值为modCount
函数:
hasNext:如果下一个元素的下标等于集合大小,说明到最后了
next:首先判断expectedModCount与modCount是否相等,然后判断cursor是否超过集合长度,然后将cursor赋值给lastRet并返回下标为lastRet的元素,最后cursor自增1.
remove:首先判断lastRet是否小于0(未开始获取值),然后判断expectedModCount与modCount是否相等,然后直接调用ArrayList的删除方法,指针指向上一个操作对象。
初始化状态
调用next方法
调用remove方法
总结
ArrayList 底层基于数组实现容量大小动态可变。
扩容机制为首先扩容为原始容量的 1.5 倍。如果1.5倍太小的话,则将我们所需的容量大小赋值给 newCapacity,如果1.5倍太大或者我们需要的容量太大,那就直接拿 newCapacity = (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE 来扩容。
扩容之后是通过数组的拷贝来确保元素的准确性的,所以尽可能减少扩容操作。
ArrayList 的最大存储能力:Integer.MAX_VALUE。
size 为集合中存储的元素的个数。
elementData.length 为数组长度,表示最多可以存储多少个元素。
如果需要边遍历边 remove ,必须使用 iterator。且 remove 之前必须先 next,next 之后只能用一次 remove。
作者:MatumbaMan
链接:https://juejin.cn/post/7031537624703565855