如果我想一次添加多个元素,而不考虑它们的顺序(对于 DFS),Java 用于 Stack 的通用 addAll() 方法是否与特定于 Stack 的 push() 的工作方式相同,只是使用一个数字的元素?
最佳答案
简短回答:在功能上,它们实现了相同的目标,但不一定以相同的方式实现。
长答案:来自 Stack#push
的文档:
Pushes an item onto the top of this stack. This has exactly the same effect as:
addElement(item)
此外,Vector#addElement
说:
Adds the specified component to the end of this vector
因此,push
附加到 Vector
的末尾。
现在,来自 Vector#addAll
的文档:
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.
这与在每个元素上调用 addElement
具有相同的效果,因此(通过扩展)与在每个元素上调用 push
具有相同的效果。
也就是说,addAll
可能会更有效率。
关于Java:Stack.addAll 和单独推送元素一样吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50122995/