老生常谈的关于List的效率问题

独戾 2016-11-11 03:25:34
public static long getLinkedListAddTime(){
LinkedList<String> list = new LinkedList<String>();
long start = System.currentTimeMillis();
for (int i = 0; i < 771000; i++) {
list.add("s");
}
long end = System.currentTimeMillis();
return end-start;
}


public static long getArrayListAddTime(){
ArrayList<String> list = new ArrayList<String>();
long start = System.currentTimeMillis();
for (int i = 0; i < 771000; i++) {
list.add("s");
}
long end = System.currentTimeMillis();
return end-start;
}

public static void main(String[] args) {
System.out.println(getLinkedListAddTime());
System.out.println(getArrayListAddTime());
}
我直接用add(object o)这个方法添加的话,2个list比较添加的时间,发现反而linkedList的时间耗费的多。
然而我改成add(int i,Object o)这个方法的话,结果则是正常的,也就是大家常说的ArrayList添加耗时更多,LinkedList耗时较少。
我看了一下ArrayList的add(int i,Object o)和add(object o)基本上都是差不多的
/**
* Appends the specified element to the end of this list.
*
* @param e element to be appended to this list
* @return <tt>true</tt> (as specified by {@link Collection#add})
*/
public boolean add(E e) {
ensureCapacity(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}

/**
* Inserts the specified element at the specified position in this
* list. Shifts the element currently at that position (if any) and
* any subsequent elements to the right (adds one to their indices).
*
* @param index index at which the specified element is to be inserted
* @param element element to be inserted
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public void add(int index, E element) {
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++;
}
有没有懂的大牛来给小兵解答一下这个问题,非常感谢!!!!!
...全文
303 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
ArrayList底层实现是数组,插入元素的话当然很麻烦,后面的元素都要移位 LinkedList底层是链表,插入元素,只要打断这个节点插入元素即可。
独戾 2016-11-11
  • 打赏
  • 举报
回复
少说了很重要的一点 for循环里如果写add(0,“s”);才会得到理想的结果,如果写成add(i,“s”);那么仍然是得到相反的结果

62,626

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧