public void ensureCapacity(int minCapacity) {
modCount++;
int oldCapacity = 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);
}
}
(5)当删除元素时,会把数组内从被删除的元素后的所有元素,向前移动一位, 代价很高
public E remove(int index) {
RangeCheck(index);
modCount++;
E oldValue = (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;
}
(6) 注: ctr+sft+w 在Eclipse中关闭所有窗口
输入syso 按下ctr+/ ,会快捷输入 System.out.println();
输入main 按下ctr+/ ,会快捷输入 Public staitc void main(String[ ] args)
二 LinkedList 类使用注意事项
(1) LinkedList在JDK中使用循环链表实现的, LinkedList 内部增加一个元素
public void add(int index, E element) {
addBefore(element, (index==size ? header : entry(index)));
}
private Entry addBefore(E e, Entry entry) {
Entry newEntry = new Entry(e, entry, entry.previous);
newEntry.previous.next = newEntry;
newEntry.next.previous = newEntry;
size++;
modCount++;
return newEntry;
}
private static class Entry {
E element;
Entry next;
Entry previous;
Entry(E element, Entry next, Entry previous) {
this.element = element;
this.next = next;
this.previous = previous;
}
}
private Entry entry(int index) {
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException("Index: "+index+
", Size: "+size);
Entry e = header;
if (index < (size >> 1)) {
for (int i = 0; i <= index; i++)
e = e.next;
} else {
for (int i = size; i > index; i--)
e = e.previous;
}
return e;
}
(2)内部减少一个元素
private E remove(Entry e) {
if (e == header)
throw new NoSuchElementException();
E result = e.element;
e.previous.next = e.next;
e.next.previous = e.previous;
e.next = e.previous = null;
e.element = null; size--;
modCount++;
return result;
}
三 Linkedlist 和 ArrayList 两者比较
(1) ArrayList : 不利于频繁插入和删除
(2)LinkedList : 不利于搜素