在数组中,可以通过以下方式在开头添加元素
int[] array = {1,2,3,4,5};
同样如何向队列添加多个条目?就像,
Queue<Integer> queue = {1,2,3,4,5};
有什么办法可以做到这一点吗?
最佳答案
首先,您必须选择要实例化的Queue
实现。假设您选择 LinkedList
(它实现 Queue
)。
与任何 Collection 一样,LinkedList
有一个构造函数,它接受 Collection
并将该 Collection
的元素添加到列表中。
例如:
Queue<Integer> queue = new LinkedList<>(Arrays.asList(new Integer[]{1,2,3,4,5}));
或者(正如 PaulrBear 正确评论的那样):
Queue<Integer> queue = new LinkedList<>(Arrays.asList(1,2,3,4,5));
或者您可以利用 Java 8 Streams :
Queue<Integer> queue = IntStream.of(1,2,3,4,5)
.boxed()
.collect(Collectors.toCollection(LinkedList::new));
关于java - 如何在同一条语句中初始化队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33983990/