List 接口有两个实现类,ArrayList 与LinkedList
如果排序用ArrayList 如果经常删写改 操作用 LinkedList,为什么会有这样一说法呢,我们从两个类的源码来分析。
ArrayList:
如果排序用ArrayList 如果经常删写改 操作用 LinkedList,为什么会有这样一说法呢,我们从两个类的源码来分析。
ArrayList:
数据存储类型是:
private transient Object[] elementData;//就是一个普通的对象数据。
public boolean add(E e) {//增加对象的方法,可以看出是把数组的大小改变为size+1,然后把老的对象数据复制到新的对象数据
ensureCapacity(size + 1); // Increments modCount!!
elementData[size++] = e;//最后把新添加进来的值放到最后一个位置
return true;
}
public void add(int index, E element) { //从index开始把位置往后移一位,所以效率会比较低
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++;
}
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;
}
LinkedList:
数据存储类型是:<!--WizRtf2Html Charset=0 -->private transient Entry<E> header = new Entry<E>(null, null, null);
以对象链表存储数据
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> addBefore(E e, Entry<E> entry) {//所有的ADD方法都是调用这个,
Entry<E> newEntry = new Entry<E>(e, entry, entry.previous);
newEntry.previous.next = newEntry;
newEntry.next.previous = newEntry;
size++;
modCount++;
return newEntry;
}
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;
}
所以总结出来,排序用ArrayList(对象数组) 经常删写改 操作用 LinkedList(链表)