arraylist相当于一个动态数组。创建的时候有一个默认的容量(默认为10)。
底层实现
arrylist的底层实现是object数组
//底层存放数组
transient Object[] elementData;
//实际大小
private int size;
构造方法
无参构造函数,默认容量为10。
/**
* Default initial capacity.
*/
private static final int DEFAULT_CAPACITY = 10;
/**
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
带容量参数的构造函数
比较简单,只要初始大小大于0即可。
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包含collection中的元素。分为两步实现,首先调用collection.toArray方法,虽然elementData 是object[]类型的,但是它指向的类型不一定是Object[],所以还要进行判断。调用Arrays.Copyof方法,转化为object[]类型。
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();
if ((size = elementData.length) != 0) {
// defend against c.toArray (incorrectly) not returning Object[]
// (see e.g. https://bugs.openjdk.java.net/browse/JDK-6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
// replace with empty array.
this.elementData = EMPTY_ELEMENTDATA;
}
}
增删改查
add
add方法非常简单,modcount记录被修改的次数,modcount++,然后再elementData大小加一,将元素放入末尾即可。
public boolean add(E e) {
modCount++;
add(e, elementData, size);
return true;
}
private void add(E e, Object[] elementData, int s) {
if (s == elementData.length)
elementData = grow();
elementData[s] = e;
size = s + 1;
}
这里比较有意思的是,虽然调用的是grow代码,但不一定会增加elementdata数组的长度,因为在扩展之前会进行判断。数组的长度是按照int newCapacity = oldCapacity + (oldCapacity >> 1);扩展的,也即比原来多0.5倍。
下面的方法是jdk8的
public void add(int index, E element) {
//检查index是否合法
rangeCheckForAdd(index);
//modcount++(修改次数),修改elementdata数组的大小
ensureCapacityInternal(size + 1); // Increments modCount!!
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
elementData[index] = element;
size++;
}
remove
//将index+1 ~ size-1 的元素向前移动至index的位置,返回被删除的元素
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;
}
//删除index所在元素,后面元素前移,感觉类似remove呢
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
}
//removerange 删除指定范围内的元素from(包含),to(不包含)
protected void removeRange(int fromIndex, int toIndex) {
modCount++;
int numMoved = size - toIndex;
System.arraycopy(elementData, toIndex, elementData, fromIndex,
numMoved);
// clear to let GC do its work
int newSize = size - (toIndex-fromIndex);
for (int i = newSize; i < size; i++) {
elementData[i] = null;
}
size = newSize;
}
//删除collection中的所有元素
public boolean removeAll(Collection<?> c) {
//如果包含null,则直接抛出异常
Objects.requireNonNull(c);
return batchRemove(c, false);
}
//批量移除elementdate中包含collection中的元素
private boolean batchRemove(Collection<?> c, boolean complement) {
final Object[] elementData = this.elementData;
int r = 0, w = 0;
boolean modified = false;
try {
for (; r < size; r++)
//遍历elementdata中的所有元素,如果c不包含elementdata中的元素,则将该元素放入elementdata中,w表示elementdata中存在的元素大小(collection中不包含的元素)。
if (c.contains(elementData[r]) == complement)
elementData[w++] = elementData[r];
} finally {
// Preserve behavioral compatibility with AbstractCollection,
// even if c.contains() throws.
//上面可能出现异常,导致for循环没有执行完。(所以其实会有没有完全删除collections中的元素,->删到一般抛异常了,但却返回true的情况)
if (r != size) {
System.arraycopy(elementData, r,
elementData, w,
size - r);
w += size - r;
}
//将删除的元素位置置空,方便gc
if (w != size) {
// clear to let GC do its work
for (int i = w; i < size; i++)
elementData[i] = null;
modCount += size - w;
size = w;
modified = true;
}
}
return modified;
}
//仅保存包含在collection中的元素,其余全部删除
public boolean retainAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, true);
}
get
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
E elementData(int index) {
return (E) elementData[index];
}
set
public E set(int index, E element) {
rangeCheck(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
contains
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
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;
}
trimtosize
由于size表示元素真正个数,这里可能会有很多浪费的空间需要回收。
public void trimToSize() {
modCount++;
if (size < elementData.length) {
elementData = (size == 0)
? EMPTY_ELEMENTDATA
: Arrays.copyOf(elementData, size);
}
}
扩容策略
在add的时候会调用ensureCapacityInternal方法,该方法就是进行扩容的检查。
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
- 大小检测:如果是空,则赋值为10(初始值)
- 检测是否需要进行扩容:只有数组需要的最小容量大于数组当前大小,才会进行扩容。
//大小检测
private static int calculateCapacity(Object[] elementData, int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
}
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
扩容,将大小增加原来的一半,并将原来的数组通过Arrays.copyOf方法拷贝过去,使达到新的长度大小。
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);
}
一些思考
modcount的作用
在iterator方法中会保存当前的修改次数,expectedModCount,如果在进行迭代之后又调用了arraylist的修改操作,就会抛出ConcurrentModificationException异常。
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();
}
}
比如
public static void main(String[] args) {
ArrayList<Integer> arrayList = new ArrayList<>();
arrayList.add(1);
arrayList.add(2);
arrayList.add(3);
Iterator<Integer> iterator= arrayList.iterator();
arrayList.remove(1);
while(iterator.hasNext()) {
Integer integer = iterator.next();//抛异常
if (integer == 1) {
}
}
}
四种遍历方法
- for循环
/**
* for 循环进行增删之后,后面的元素的索引会改变。比如下面删除了第一个1之后,第二个1位置前移;
* 就不会再被处理到。
*/
public static void fortest() {
ArrayList<Integer> arrayList = new ArrayList<>();
arrayList.add(1);
arrayList.add(1);
arrayList.add(2);
arrayList.add(3);
arrayList.add(4);
arrayList.add(5);
for(int i = 0; i < arrayList.size(); i++) {
Integer io = arrayList.get(i);
if(io % 2 != 0) {
arrayList.remove(i);
}
}
System.out.println(arrayList);//[1,2,4]
}
- iterator
可以调用iterator定义的remove等方法进行修改
public static void itrtest() {
ArrayList<Integer> arrayList = new ArrayList<>();
arrayList.add(1);
arrayList.add(1);
arrayList.add(2);
arrayList.add(3);
arrayList.add(4);
arrayList.add(5);
Iterator<Integer> iterator = arrayList.iterator();
while(iterator.hasNext()) {
Integer integer = iterator.next();
if(integer % 2 != 0) {
iterator.remove();
}
}
System.out.println(arrayList);//[2,4]
}
- for ( : )
/**
* for(item : obj)底层采用的是iterator的方法
* 不能进行增删等操作
*/
public static void for2test() {
ArrayList<Integer> arrayList = new ArrayList<>();
arrayList.add(1);
arrayList.add(1);
arrayList.add(2);
arrayList.add(3);
arrayList.add(4);
arrayList.add(5);
//其实这里也是走的iterator方法
//Iterator<Integer> iterator = arrayList.iterator();
//while(iterator.hasNext()) {
//Integer integer = iterator.next();
for(Integer io : arrayList) {
if(io % 2 != 0) {
//arrayList.remove(io);//抛异常
}
}
System.out.println(arrayList);
}
- foreach
public static void foreachtest() {
ArrayList<Integer> arrayList = new ArrayList<>();
arrayList.add(1);
arrayList.add(1);
arrayList.add(2);
arrayList.add(3);
arrayList.add(4);
arrayList.add(5);
//arrayList.subList(1, 3);
//foreach内部采用了for i 方法
arrayList.forEach(item -> {
if(item % 2 != 0) {
//arrayList.remove(item);
}
});
System.out.println(arrayList);//
}
总结
arraylist底层是对象数组,适合需要快速访问的场景,并且只在末尾进行增删的场景。在指定位置增加或删除,都会导致后面的元素进行移动,所以效率并不高O(N)。另外需要格外注意在循环迭代的时候,小心使用remove等方法,有些可能会导致出现和期望不同的结果(比如for循环中调用remove,导致后面的元素前移,并没有进入到for循环中–四种遍历的第一种);在使用iterator遍历之后,小心使用remove等方法,不然可能抛出异常。