[英]How to initialize a Queue in the same statement
在數組中,可以按以下方式在元素開頭添加元素
int[] array = {1,2,3,4,5};
同樣,如何將多個條目添加到隊列中? 喜歡,
Queue<Integer> queue = {1,2,3,4,5};
有什么辦法嗎?
首先,您必須選擇要實例化的Queue
實現。 假設您選擇的是LinkedList
(實現Queue
)。
像任何集合, 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));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.