其他的方法
trimToSize方法
- 收缩到size大小,如果size=0,就为空数组实例。
1
2
3
4
5
6
7
8public void trimToSize() {
modCount++;
if (size < elementData.length) {
elementData = (size == 0)
? EMPTY_ELEMENTDATA
: Arrays.copyOf(elementData, size);
}
}
ensureCapacity方法
1 | public void ensureCapacity(int minCapacity) { |
lastIndexOf方法
- 从末尾开始寻找元素
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21public int lastIndexOf(Object o) {
return lastIndexOfRange(o, 0, size);
}
int lastIndexOfRange(Object o, int start, int end) {
Object[] es = elementData;
if (o == null) {
for (int i = end - 1; i >= start; i--) {
if (es[i] == null) {
return i;
}
}
} else {
for (int i = end - 1; i >= start; i--) {
if (o.equals(es[i])) {
return i;
}
}
}
return -1;
}
clone()
- 浅拷贝
1
2
3
4
5
6
7
8
9
10
11public Object clone() {
try {
ArrayList<?> v = (ArrayList<?>) 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(e);
}
}
toArray()
- 无参的toArray返回ArrayList元素的Object数组,
T[] toArray(T[] a)接收一个缓冲数组来存放ArrayList容器里的元素,如果a.length大于size则会在a[size]处设为null,返回对a数组的引用 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
41public Object[] toArray() {
return Arrays.copyOf(elementData, size);
}
public <T> T[] toArray(T[] a) {
if (a.length < size)
// Make a new array of a's runtime type, but my contents:
return (T[]) Arrays.copyOf(elementData, size, a.getClass());
System.arraycopy(elementData, 0, a, 0, size);
if (a.length > size)
a[size] = null;
return a;
}
Arrays:
public static <T> T[] copyOf(T[] original, int newLength) {
return (T[]) copyOf(
original, newLength, original.getClass()
);
}
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
T[] copy = ((Object)newType == (Object)Object[].class)
? (T[]) new Object[newLength]
: (T[]) Array.newInstance(newType.getComponentType(), newLength);
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}
public static Object newInstance(
Class<?> componentType,int length
)throws NegativeArraySizeException
//创建具有指定组件类型和长度的新数组。 调用此方法相当于创建一个数组,如下所示
int[] x = {length};
Array.newInstance(componentType, x);
类型转换
1 | E elementData(int index) { |
比较
1 | public boolean equals(Object o) { |