文章目录
  1. 1. ArrayList简介
  2. 2. 运行环境
  3. 3. ArrayList源码分析
  4. 4. 对ArrayList的总结

ArrayList简介

ArrayList是List接口的一个实现,是基于数组实现的,容量可以进行动态增加。ArrayList不是线程安全的,如果需要在多线程中使用推荐使用Collections.synchronizedList(List<T> list) 方法创建线程安全的List集合,或者使用concurrent包下的CopyOnWriteArrayList<>() 类创建线程安全的类

运行环境

  • OS:Win7 64bit
  • idea:IntelliJ IDEA 2017
  • jdkVersion:1.7.0_79 64 bit
  • 使用的pom.xml:无

ArrayList源码分析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
package java.util;
/**
* @author Josh Bloch
* @author Neal Gafter
* @see Collection
* @see List
* @see LinkedList
* @see Vector
* @since 1.2
*/
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
private static final long serialVersionUID = 8683452581122892189L;
/**
* 默认初始化容量
*/
private static final int DEFAULT_CAPACITY = 10;
/**
* 用来共享的空数组实例
*/
private static final Object[] EMPTY_ELEMENTDATA = {};
/**
* The array buffer into which the elements of the ArrayList are stored.
* ArrayList存储在该数组中,容量就是数组的大小。任何空的ArrayList的elementData和EMPTY_ELEMENTDATA相等。
* 当添加第一个元素的时候容量扩展为DEFAULT_CAPACITY
*/
private transient Object[] elementData;
/**
* ArrayList的size,这个数字是ArrayList的内容个数
* @serial
*/
private int size;
/**
* 该构造方法创建一个空的list初始化容量是由参数指定的
* @param initialCapacity the initial capacity of the list
* @throws IllegalArgumentException if the specified initial capacity
* is negative
*/
public ArrayList(int initialCapacity) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity];
}
/**
* Constructs an empty list with an initial capacity of ten. 这是1.6版本的注释,
* 现在这个版本默认创建后是0长度的数组,第一次添加时才初始化容量
* 空的构造方法,默认是空的数组
*/
public ArrayList() {
super();
this.elementData = EMPTY_ELEMENTDATA;
}
/**
* 这是1.6版本的空构造方法
*
*/
public ArrayList() {
this(10);
}
/**
*构造一个包含指定集合的元素的列表,按照它们由集合的迭代器返回的顺序。
* @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();
size = elementData.length;
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
}
/**
* 将集合的数组长度变成和集合size
*/
public void trimToSize() {
modCount++;
if (size < elementData.length) {
elementData = Arrays.copyOf(elementData, size);
}
}
/**
* 添加集合的容量,确保增加指定参数的最小容量。其实也就是先往小的加
*/
public void ensureCapacity(int minCapacity) {
int minExpand = (elementData != EMPTY_ELEMENTDATA)
// any size if real element table
? 0
// larger than default for empty table. It's already supposed to be
// at default size.
: DEFAULT_CAPACITY; //如果list集合为空返回默认的大小
if (minCapacity > minExpand) {
ensureExplicitCapacity(minCapacity);
}
}
private void ensureCapacityInternal(int minCapacity) {
if (elementData == 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);
}
/**
* 数组最大能分配的值
* 一些虚拟机保留了一些头信息
* 尝试分配一些大的数组可能的结果是OutOfMemoryError,请求数组的size超过了VM限制
*/
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
/**
* 添加集合的容量,确保增加指定参数的最小容量。其实也就是先往小的加
*/
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;
}
/**
* 返回该list的元素个数
* @return the number of elements in this list
*/
public int size() {
return size;
}
/**
* 如果该list不包含任何元素则返回true
* @return <tt>true</tt> if this list contains no elements
*/
public boolean isEmpty() {
return size == 0;
}
/**
* 如果该list包含指定的元素则返回true
*/
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
/**
* 返回的第一个匹配指定元素的索引,如果返回-1表示这个list集合没有包含该元素。
* 更加准确的说是返回匹配的最小的索引,从0开始到size进行循环
*/
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;
}
/**
* 反向查询元素,如果返回-1表示这个list集合没有包含该元素。
* 更加准确的说是返回匹配的最大的索引,从size开始到0进行循环
*/
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;
}
/**
* 复制集合
* @return a clone of this <tt>ArrayList</tt> instance
*/
public Object clone() {
try {
@SuppressWarnings("unchecked")
ArrayList<E> v = (ArrayList<E>) super.clone();
v.elementData = Arrays.copyOf(elementData, size);
v.modCount = 0;
return v;
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError();
}
}
/**
* 将集合转换成数组,该数组包含集合的所有元素。该数组的元素顺序和list集合一致
* 该方法会新创建一个数组实例
*/
public Object[] toArray() {
return Arrays.copyOf(elementData, size);
}
/**
* 将集合转换成数组返回
*/
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
if (a.length < size)
// 如果传入的数组长度小于size则会新建一个array,该array的长度等于集合的size
return (T[]) Arrays.copyOf(elementData, size, a.getClass());
//否则还是使用传入的数组,并将集合元素复制到数组中
System.arraycopy(elementData, 0, a, 0, size);
if (a.length > size)
//将传入数组索引为集合size的值置为null
a[size] = null;
return a;
}
// 数组随机访问
@SuppressWarnings("unchecked")
E elementData(int index) {
return (E) elementData[index];
}
/**
* 返回指定索引元素
*/
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
/**
* 替换指定索引元素,并返回被替换的元素
*/
public E set(int index, E element) {
rangeCheck(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
/**
* 追加指定的元素到集合的末尾,第一次添加的时候会指定数组的默认length。
* 这个和1.6版本不同
*/
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);//这里涉及到数组的复制,这就导致ArrayList随机添加消耗很大。
//如果index较小,size很大。则需要复制的元素是size-index
elementData[index] = element;//将指定元素添加到指定索引
size++;
}
/**
* 移除一个元素,如果这个元素不是最后还涉及元素移动的操作
*/
public E remove(int index) {
rangeCheck(index);//校验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;
}
/**
* 这个和索引remove一样,只是多了一步查找元素索引的操作。
*/
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;
}
/*
* 参考remove(int index)方法
*/
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
}
/**
* 清除集合中的所有元素
*/
public void clear() {
modCount++;
// clear to let GC do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
/**
* 添加指定的集合到该ArrayList的的最后,如果有其他线程修改了入参,
* 将不会影响该方法的操作
*/
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;
}
/**
* 参考addAll(Collection<? extends E> c)方法,该方法增加了元素的移动
*/
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;
}
/**
* 移除给定范围内的数据
*/
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;
}
/**
* 越界校验
*/
private void rangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
/**
* 校验合法的索引
*/
private void rangeCheckForAdd(int index) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
/**
* 异常信息组装
*/
private String outOfBoundsMsg(int index) {
return "Index: "+index+", Size: "+size;
}
/**
* 移除给定集合包含的元素
*/
public boolean removeAll(Collection<?> c) {
return batchRemove(c, false);
}
/**
* 保留给定集合的元素
*/
public boolean retainAll(Collection<?> c) {
return batchRemove(c, true);
}
//批量移除
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++)
if (c.contains(elementData[r]) == complement)
elementData[w++] = elementData[r];
} finally {
// Preserve behavioral compatibility with AbstractCollection,
// even if c.contains() throws.
if (r != size) {
System.arraycopy(elementData, r,
elementData, w,
size - r);
w += size - r;
}
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;
}
}

对ArrayList的总结

  • ArrayList底层是使用数组实现的,随机访问效率高,随机删除和动态扩容效率低
  • 无参构造方法和jdk1.6不一样,初始化后是不会马上分配数组的大小的,而是在第一次add的时候进行分配
  • 在随机删除和随机添加时涉及到内存移动比较耗时,数组length扩容的时候也涉及内存复制。效率不高
  • ArrayList扩容时设置新的容量为旧容量的1.5倍加1,如果设置的新容量不够,则直接将新容量设置为传入的参数
文章目录
  1. 1. ArrayList简介
  2. 2. 运行环境
  3. 3. ArrayList源码分析
  4. 4. 对ArrayList的总结