ArrayList源码常用方法分析
1.基础信息
- 底层实现为数组,查询、修改快;增删慢。
- 元素可以重复,可以为null
- 线程不安全
LinkedList:链表实现,查询慢,增删快;元素可以重复,可以为null;线程不安全
Vector:数组实现,查询快,增删慢;元素可以重复,可以为null;线程安全,但也会触发fail-fast机制。
2.初始化
- 无参构造
- 初始容量参数构造
- 集合参数构造
2.1无参构造
List<String> arr = new ArrayList<String>();
无参构造时,默认生成长度为10的底层数组。
/**
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
2.2初始容量参数构造
List<String> arr = new ArrayList<String>(20);
- 容量参数<0,直接返回异常
- 容量参数=0,与无参构造类似,生成长度为10的底层数组
- 容量参数>0,生成的底层数组Object[]长度即为参数大小
/**
* Constructs an empty list with the specified initial capacity.
*
* @param initialCapacity the initial capacity of the list
* @throws IllegalArgumentException if the specified initial capacity
* is negative
*/
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);
}
}
2.3集合参数构造
List<String> list = new ArrayList<String>();
list.add("0");
list.add("1");
list.add("2");
LinkedList<String> linkedList = new LinkedList<String>();
linkedList.add("3");
linkedList.add("4");
linkedList.add("5");
Vector<String> vector = new Vector<String>();
vector.add("6");
vector.add("7");
vector.add("8");
List<String> arr1 = new ArrayList<String>(list);
List<String> arr2 = new ArrayList<String>(linkedList);
List<String> arr3 = new ArrayList<String>(vector);
for (String string : arr1) {
System.out.println(string);
}
for (String string : arr2) {
System.out.println(string);
}
for (String string : arr3) {
System.out.println(string);
}
- 传入的集合必须继承Collection接口
- 如果集合为null,将出现空指针异常错误。因为需要将集合转化为Array,即Object[]数组
- 集合数据长度为0,将与无参构造类似,生成长度为10的底层数组
- 集合数据长度不为0,先判断集合是否已正确转换为Object[]。如果没正确转换,将使用Arrays.copyOf()进行转换。
/**
* 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) {
// 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;
}
}
3.add(E e)
- size+1,判断已有的数据数组是否为空,为空则与默认容量10比较并选择较大的一方
- modCount++,判断是否需要扩容;如果不用扩容,直接elementData[size++] = e;
- 扩容:使用Arrays.copyOf生成新的长度为原来1.5倍的数组, int newCapacity = oldCapacity + (oldCapacity >> 1);
- 扩容后长度大于MAX_ARRAY_SIZE:(2^31-1)-8,那么扩容后长度为2^31-1,即Integer的最大值
/**
* Appends the specified element to the end of this list.
*
* @param e element to be appended to this list
* @return <tt>true</tt> (as specified by {@link Collection#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);
}
/**
* Increases the capacity to ensure that it can hold at least the
* number of elements specified by the minimum capacity argument.
*
* @param minCapacity the desired minimum capacity
*/
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;
}
4.modeCount与异常
* <p><b>Use of this field by subclasses is optional.</b> If a subclass
* wishes to provide fail-fast iterators (and list iterators), then it
* merely has to increment this field in its {@code add(int, E)} and
* {@code remove(int)} methods (and any other methods that it overrides
* that result in structural modifications to the list). A single call to
* {@code add(int, E)} or {@code remove(int)} must add no more than
* one to this field, or the iterators (and list iterators) will throw
* bogus {@code ConcurrentModificationExceptions}. If an implementation
* does not wish to provide fail-fast iterators, this field may be
* ignored.
*/
protected transient int modCount = 0;
4.1ConcurrentModificationException并发修改异常
用于判断在遍历(迭代器、for-each,在jdk1.8版本中均异常)时,列表中的元素是否发生结构性变化(比如增、删会修改)操作。如果在遍历时出现结构性变化将出现异常并发修改异常java.util.ConcurrentModificationException。
List<String> list = new ArrayList<String>();
list.add("0");
list.add("1");
list.add("2");
List<String> arr1 = new ArrayList<String>(list);
for (String string : arr1) {
if("2".equals(string)) {
arr1.add("haha");
}
System.out.println(string);
}
Iterator<String> iterator = arr1.iterator();
while(iterator.hasNext()) {
String next = iterator.next();
if("2".equals(next)) {
arr1.add("haha");
}
if("0".equals(next)) {
arr1.remove("1");
}
System.out.println(next);
}
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
at java.util.ArrayList$Itr.next(ArrayList.java:851)
at list.ListDemo.main(ListDemo.java:18)
4.2java.lang.IndexOutOfBoundsException
List<String> list = new ArrayList<String>();
list.add("0");
list.add("1");
list.add("2");
List<String> arr1 = new ArrayList<String>(list);
Iterator<String> iterator = arr1.iterator();
for(int i =0;iterator.hasNext(); i++) {
arr1.remove(i);
}
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 1
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.remove(ArrayList.java:492)
at list.ListDemo.main(ListDemo.java:22)