早上来公司利用一点时间看了下ArrayList的源码,以前也看过,好久没碰有点模糊了,于是今天再看了一次:
ArrayList是JAVA中常用的集合类,是List接口的可变数组的实现,并且允许包括NULL在内的所有元素。
通过查看ArrayList可以看到有三个构造方法:
public ArrayList(int initialCapacity) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity];
}
public ArrayList() {
this(10);
}
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);
}
从代码中可以看出我们常用的默认构造方法初始化的容量大小为10的数组,原来所说的集合是数组来实现的。
public void ensureCapacity(int minCapacity) {
modCount++;
int ldCapacity = elementData.length;
if (minCapacity > oldCapacity) {
Object oldData[] = elementData;
int newCapacity = (oldCapacity * 3)/2 + 1;
if (newCapacity < minCapacity)
newCapacity = minCapacity;
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);
}
}
public boolean add(E e) {
ensureCapacity(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
看这个方法ensureCapacity,这个方法觉得有点奇怪,里面有个公式大约为1.5倍加1。这个就是ArrayList扩容的操作,在ArrayList的add方法中就会先调用这个扩容的方法(如果满了就会自动扩容)。
add还有一个重载的方法:
public void add(int index, E element) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(
"Index: "+index+", Size: "+size);
ensureCapacity(size+1); // Increments modCount!!
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
elementData[index] = element;
size++;
}
这个为指定位置往ArrayList中存储值,如果指定位置有值,就会将指定位置及指定位置后面的值往后移动一位,将新值放入指定位置。
public E get(int index) {
RangeCheck(index);
return (E) elementData[index];
}
public E remove(int index) {
RangeCheck(index);
modCount++;
E ldValue = (E) elementData[index];
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // Let gc do its work
return oldValue;
}
private void RangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(
"Index: "+index+", Size: "+size);
}
看,是不是见到了自己经常见到的异常,下标越阶。
ArrayList中还有一些其它的方法,不一一说了,这里需要注意的就是ArrayList自动扩容:
我们最好能够一次指定ArrayList的大小,尽量避免ArrayList自动扩容,如果真有需要可以通过调用ensureCapacity方法进行手动扩容。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/25285600/viewspace-772446/
,如需转载,请注明出处,否则将追究法律责任。