Java:Stack.addAll是否与单独推送元素相同?

时间:2018-05-01 19:58:07

标签: java stack

如果我想一次添加多个元素,无论它们的顺序如何(对于DFS),Java的Stack的通用addAll()方法与Stack特定的push()的工作方式相同,只是一个数字元素?

2 个答案:

答案 0 :(得分:3)

由Vector.addAll定义的Nope,Stack的实现,如下所示:

/**
 * Appends all of the elements in the specified Collection to the end of
 * this Vector, in the order that they are returned by the specified
 * Collection's Iterator.  The behavior of this operation is undefined if
 * the specified Collection is modified while the operation is in progress.
 * (This implies that the behavior of this call is undefined if the
 * specified Collection is this Vector, and this Vector is nonempty.)
 */
public synchronized boolean addAll(Collection<? extends E> c) {
    modCount++;
    Object[] a = c.toArray();
    int numNew = a.length;
    ensureCapacityHelper(elementCount + numNew);
    System.arraycopy(a, 0, elementData, elementCount, numNew);
    elementCount += numNew;
    return numNew != 0;
}

所以它并不只是在循环中调用push。

我们可以将其与Vector.addElement调用的Stack.push函数进行比较:

public synchronized void addElement(E obj) {
    modCount++;
    ensureCapacityHelper(elementCount + 1);
    elementData[elementCount++] = obj;
}

如果你在一个循环中调用了push,那么至少需要多次调用ensureCapacityHelper。因此,正如您所料,我怀疑 addAll有更好的表现。

答案 1 :(得分:2)

简短回答:从功能上讲,他们实现了相同的目标,但不一定以同样的方式。

答案很长:来自Stack#push的文档:

  

将项目推到此堆栈的顶部。这与以下效果完全相同:    addElement(item)

此外,Vector#addElement说:

  

将指定的组件添加到此向量的末尾

因此,push附加到Vector

的末尾

现在,来自Vector#addAll的文档:

  

将指定Collection中的所有元素按照指定Collection的迭代器返回的顺序追加到此Vector的末尾。

这与在每个元素上调用addElement具有相同的效果,因此(通过扩展)在每个元素上调用push的效果相同。

尽管如此,addAll可能会更有效地做事。