ArrayList add(索引,对象)vs add(对象)复杂度

时间:2016-03-11 05:19:58

标签: java performance arraylist

我的APCS课程中有一个关于向ArrayList添加元素的小选择问题,虽然一个特定的答案在我看来是直观正确的(选择B),但我不完全确定它是否确实是正确的或实际上是什么在幕后表现明智:

//Consider the following methods
public static List<Integer> process1(int n) {
    List<Integer> someList = new ArrayList<Integer>();
    for (int k = 0; k < n; k++) {
        someList.add(new Integer(k));
    }
    return someList;
}
public static List<Integer> process2(int n) {
    List<Integer> someList = new ArrayList<Integer>();
    for (int k = 0; k < n; k++) {
        someList.add(k, new Integer(k));
    }
    return someList;
}

//Which of the following best describes the behavior of process1 and process2?
//(A) Both methods produce the same result and take the same amount of time
//(B) Both methods produce the same result and process1 is faster than process2
//(C) The two methods produce different results and process1 is faster than process2
//(D) The two methods produce different results and process2 is faster than process1

注意:我使用足够大的参数在我的计算机上测试了这两种方法,并且两者在运行长度上非常接近,但是method1似乎稍快一些。此外,这不是一个要上交的作业问题,所以不必担心给我提供答案:)

2 个答案:

答案 0 :(得分:1)

the JDK source(在@ ScaryWombat的回答中再现)看来,第一个会稍快一些。

在上下文中,System.arraycopy实际上不会执行任何操作,但仍会进行调用。否则,它们基本相同。第一个有一个额外的函数调用,因此它可能会慢一点 tiny 位(放大n)。

答案 1 :(得分:0)

 public boolean add(E e) {
         ensureCapacity(size + 1);  // Increments modCount!!
         elementData[size++] = e;
         return true;
}

VS

public void add(int index, E element) {
         rangeCheckForAdd(index);

         ensureCapacity(size+1);  // Increments modCount!!
         System.arraycopy(elementData, index, elementData, index + 1,
                          size - index);
         elementData[index] = element;
         size++;
     }

所以看起来除了两者共享的公共代码之外,方法还有更多的代码要做。