用java源代码学数据结构<三>:ArrayList 详解(二)

2014-11-24 08:51:45 · 作者: · 浏览: 10
itCapacity(minCapacity);
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
/*
The maximum size of array to allocate.
有些VM需要在数组前加些头信息(header words )
*/
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
//Increases the capacity to ensure that it can hold at least the
// number of elements specified by the minimum capacity argument.
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
//默认是增加原来oldcapacity的一半(重点)
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;
}
//实际元素数目,和vector方法类似
public int size() {
return size;
}
//是否为空
public boolean isEmpty() {
return size == 0;
}
//是否包含o对象
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
////index为起始位置,返回-1表示不包含o对象
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;
}
//反向查找
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;
}
public Object clone() {
try {
@SuppressWarnings("unchecked")
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();
}
}
public Object[] toArray() {
return Arrays.copyOf(elementData, size);
}
//通过将对象置为null,来删除对象内存空间
@SuppressWarnings("unchecked")
public 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;
}
@SuppressWarnings("unchecked")
E elementData(i