ArrayList最重要的基本方法Api:
set(int idx, AnyType newVak)
向目標(biāo)索引idx設(shè)置值 newVal
public AnyType set(int idx, AnyType newVal) {
if (idx < 0 || idx >= size()) {
throw new ArrayIndexOutOfBoundsException();
}
AnyType old = theItems[idx];
theItems[idx] = newVal;
return old;
}
get(int idx)
讀取目標(biāo)索引idx的值
public AnyType get(int idx) {
if (idx < 0 || idx >= size()) {
throw new ArrayIndexOutOfBoundsException();
}
return theItems[idx];
}
ensureCapacity(int newCapacity)
可以叫擴(kuò)容為newCapacity方法.
public void ensureCapacity(int newCapacity) {
/*theSize 數(shù)組實際大小*/
if (newCapacity < theSize) {
return;
}
/*創(chuàng)建新的數(shù)組,然后復(fù)制老數(shù)組值入新數(shù)組*/
AnyType[] old = theItems;
theItems = (AnyType[]) new Object[newCapacity];
for (int i = 0; i < size(); i++) {
theItems[i] = old[i];
}
}
size()
返回list的大小
public int size() {
return theSize;
}
add()
添加元素
public boolean add(AnyType x) {
add(size(), x);
return true;
}
public void add(int idx, AnyType x) {
/*當(dāng)存值得數(shù)組大小和list大小相等時,把存值數(shù)組擴(kuò)容為1倍*/
if (theItems.length == size()) {
ensureCapacity(2 * theItems.length);
}
/*如果是在數(shù)組中間插入,后面的元素要向高位移動*/
for (int i = theSize; i > idx; i--) {
theItems[i] = theItems[i - 1];
}
theItems[idx] = x;
theSize++;
}
remove(int idx)
刪除指定位置的元素
public AnyType remove(int idx) {
AnyType removeItem = theItems[idx];
/*如果刪除的元素是不是尾,那就需要高位向前移動*/
for (int i = idx; i < size() - 1; i++) {
theItems[i] = theItems[i + 1];
}
theSize--;
return removeItem;
}