今天看 ArrayList 的源码,有点儿搞糊涂了,一共三个构造方法:
transient Object[] elementData;
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
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);
}
}
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
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;
}
}
最常用的无参构造方法,直接将 DEFAULTCAPACITY_EMPTY_ELEMENTDATA
赋值给了 elementData
,而 DEFAULTCAPACITY_EMPTY_ELEMENTDATA
是个空数组,但是在注释上是这样写的:
Constructs an empty list with an initial capacity of ten.
搜了一圈,好多文章写的也是 10,究竟哪里出了问题?有大佬来讲讲吗?
1
YIsion 2019-07-14 01:33:53 +08:00 via Android 1
忘了从哪看的,创建出来是 0,第一次使用才会初始成默认的
|
2
wleexi 2019-07-14 01:46:27 +08:00
分析源码一定要有版本的观念。不说版本都是耍流氓
|
5
xupefei 2019-07-14 02:30:01 +08:00
```
private static final int DEFAULT_CAPACITY = 10; public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! ... private void ensureCapacityInternal(int minCapacity) { if (elementData == EMPTY_ELEMENTDATA) minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity); ensureExplicitCapacity(minCapacity); ``` 明白了吗? |
6
zazalu 2019-07-22 08:58:33 +08:00
是一个标记,下次使用的时候,如果遇到这个标记,就会扩展为默认容量 10
|