2019独角兽企业重金招聘Python工程师标准>>>
频繁插入或删除时推荐使用LinkedList而不是ArrayList
现在来查看LinkedList和ArrayList的源码及操作(LinkedList和ArrayList的PK)
插入元素时ArrayList(arraycopy方法)会拷贝遍历每个元素一遍,而LinkedList双链表仅引用地址进行修改
//ArrayList之add方法核心源码
public static
@SuppressWarnings("unchecked")
T[] copy = ((Object)newType == (Object)Object[].class)
? (T[]) new Object[newLength]
: (T[]) Array.newInstance(newType.getComponentType(), newLength);
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}
//LinkedList之add方法核心源码
void linkLast(E e) {
final Node
final Node
last = newNode;
if (l == null)
first = newNode;
else
l.next = newNode;
size++;
modCount++;
}
删除元素时ArrayList(arraycopy方法)会拷贝遍历每个元素一遍并把index元素向前移动一位,最后元素空出,而LinkedList双链表仅引用地址进行变更
//ArrayList之remove方法核心源码
public E remove(int index) {
rangeCheck(index);
modCount++;
E oldValue = elementData(index);
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work
return oldValue;
}
//LinkedList之remove方法核心源码
E unlink(Node
// assert x != null;
final E element = x.item;
final Node
final Node
if (prev == null) {
first = next;
} else {
prev.next = next;
x.prev = null;
}
if (next == null) {
last = prev;
} else {
next.prev = prev;
x.next = null;
}
x.item = null;
size--;
modCount++;
return element;
}
进行性能测试对比用例
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class Test48
{
public static List dataList = new ArrayList<>();
public static LinkedList dataLinkedList = new LinkedList<>();
public static void main(String[] args)
throws Exception
{
System.out.println("===============add方法插入数据PK=====================");
// 开始时间
Long currentTime = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++ )
{
dataList.add(i);
}
System.out.println("dataList插入所用的时间为:" + (System.currentTimeMillis() - currentTime));
// 重新赋值
currentTime = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++ )
{
dataLinkedList.add(dataList);
}
System.out.println("dataLinkedList插入所用的时间为:" + (System.currentTimeMillis() - currentTime));
System.out.println("===============remove方法删除数据PK=====================");
currentTime = System.currentTimeMillis();
for (int i = 0; i < 10000; i++ )
{
dataList.remove(i);
}
System.out.println("dataList删除所用的时间为:" + (System.currentTimeMillis() - currentTime));
// 重新赋值
currentTime = System.currentTimeMillis();
for (int i = 0; i < 10000; i++ )
{
dataLinkedList.remove(dataList);
}
System.out.println("dataLinkedList删除所用的时间为:" + (System.currentTimeMillis() - currentTime));
}
}
执行结果:
===============add方法插入数据PK=====================
dataList插入所用的时间为:38
dataLinkedList插入所用的时间为:26
===============remove方法删除数据PK=====================
dataList删除所用的时间为:3905
dataLinkedList删除所用的时间为:1
参照来源:《编写高质量代码:改善java程序的151建议》