一 ArryaList 类使用注意事项 及源代码实现
(1) ArrayaList 里面能够放各种类型的对象,但只能放对象,不能放置原生数据类型,整个集合都是如此 ;底层使用数组使用
(2) 不带泛型的ArrayList里面的对象, 取出来的时候是Object 需要强制转换为实际的对象类型;如果使用toArray方法,返回的也是Object的数组,不能直接将object数组转换为实际对象类型,需要通过for 循环一个个的进行强制转换
(3) ArrayList 的toString 方法,会调用里面各个对象的toString 方法
(4) 当新增元素时,ArrayList 会在内部先调用 ensureCapacity方法,确保数组的容量大小
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 workreturn 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<E> addBefore(E e, Entry<E> entry) {
Entry<E> newEntry = new Entry<E>(e, entry, entry.previous);
newEntry.previous.next = newEntry;
newEntry.next.previous = newEntry;
size++;
modCount++;
return newEntry;
}
private static class Entry<E> {
E element;
Entry<E> next;
Entry<E> previous;Entry(E element, Entry<E> next, Entry<E> previous) {
this.element = element;
this.next = next;
this.previous = previous;
}
}
private Entry<E> entry(int index) {
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException("Index: "+index+
", Size: "+size);
Entry<E> 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> 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 : 不利于搜素