ArrayList是List接口的一個可變長數組實現
ArrayList使用一個Object的數組存儲元素
private transient Object elementData[];
ArrayList實現了java
public boolean add(Object o)
{
ensureCapacity(size +
// Increments modCount!!
elementData[size++] = o;
return true;
}
注意這兒的ensureCapacity()方法
public Object remove(int index)
{
RangeCheck(index);
modCount++;
Object oldValue = elementData[index];
int numMoved = size
if (numMoved >
System
index+
numMoved);
elementData[
// Let gc do its work
return oldValue;
}
RangeCheck()的作用是進行邊界檢查
modCount的作用將在下面的
注
在實例化一個ArrayList時
ArrayList list = new ArrayList();
則使用缺省的容量
public ArrayList()
{
this(
}
ArrayList提供了四種add()方法
public boolean add(Object o)
public void add(int index
public boolean addAll(Collection c)
public boolean addAll(int index
在每一種add()方法中
public void ensureCapacity(int minCapacity)
{
modCount++;
int oldCapacity = elementData
if (minCapacity > oldCapacity)
{
Object oldData[] = elementData;
int newCapacity =
(oldCapacity *
if (newCapacity < minCapacity)
newCapacity = minCapacity;
elementData = new Object[newCapacity];
System
}
}
從這個方法實現中可以看出ArrayList每次擴容
public boolean add(Object o)
{
ensureCapacity(size +
// Increments modCount!!
elementData[size++] = o;
return true;
}
在父類AbstractList中定義了一個int型的屬性
protected transient int modCount =
在ArrayList的所有涉及結構變化的方法中都增加modCount的值
注
public Iterator iterator()
{
return new Itr();
}
Itr實現了Iterator()接口
int expectedModCount = modCount;
注
在Itr
public boolean hasNext()
{
return cursor != size();
}
調用了AbstractList的size()方法
在Itr
public Object next() {
try {
Object next = get(cursor);
checkForComodification();
lastRet = cursor++;
return next;
} catch(IndexOutOfBoundsException e) {
checkForComodification();
throw new NoSuchElementException();
}
}
注意
final void checkForComodification()
{
if (modCount != expectedModCount)
throw new
ConcurrentModificationException();
}
現在對modCount和expectedModCount的作用應該非常清楚了
ArrayList實現了java
private static final long
serialVersionUID =
private transient Object elementData[];
private int size;
可以看出serialVersionUID和size都將自動序列化到介質中
為什麼要這樣實現?因為elementData數組中存儲的
private synchronized void writeObject
(java
throws java
{
// Write out element count
and any hidden stuff
s
// Write out array length
s
// Write out all elements
in the proper order
for (int i=
s
}
這樣元素數組elementData中的所以元素對象就可以正確地序列化到存儲介質了
private synchronized void readObject
(java
throws java
ClassNotFoundException
{
// Read in size
hidden stuff
s
// Read in array length
and allocate array
int arrayLength = s
elementData =
new Object[arrayLength];
// Read in all elements
in the proper order
for (int i=
elementData[i] = s
}
From:http://tw.wingwit.com/Article/program/Java/hx/201311/27063.html