public void traverse(Node root){
ArrayDeque<Node> queue = new ArrayDeque<Node>();
queue.add(root);
while(!queue.isEmpty()){
Node currentNode = queue.pollFirst();
List<Node> nl = getChildrenfromDB(currentNode);
queue.addAll(nl);
}
我如何让addAll(nl)
将整个集合(List<Node>
)添加到队列的前面?
答案 0 :(得分:8)
没有任何内置功能。但是模拟很简单 - 只需按相反的顺序迭代列表并添加元素。这样他们就会以正确的顺序进入队列。
for (int i = list.size() - 1; i >=0; i--) {
queue.addFirst(node);
}
向后迭代的其他方法是:
LinkedList
的降序迭代器Collections.reverse(..)
选择一个适合您的情况。
答案 1 :(得分:8)
其实我在寻找同样的东西,这对我有用!!
samplelist.addAll(0,items); // 0 is the index where items are added on the list