java 如果我们知道元素,则直接在java中创建linkedList

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6299344/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 15:15:54  来源:igfitidea点击:

Creation of linkedList in java directly if we know the elements

java

提问by Saurabh Kumar

  List<String> ll = new LinkedList<String>("String1","String2",...);

I want something like above. Is the above line possible in java...?

我想要像上面那样的东西。上面的行在java中可能吗...?

回答by ratchet freak

not directly but

不是直接而是

List<String> ll = new LinkedList<String>(Arrays.asList("String1","String2",...));

is what you're looking for

是你要找的

回答by jvdneste

Have a look at Guava. It provides various static utility functions (and much much more), such as

看看番石榴。它提供了各种静态实用功能(以及更多),例如

Lists.newArrayList("a", "b", "c")

and similar for other data structures

和其他数据结构类似

回答by Andrew Lazarus

An alternative approach using double-braces is shown in thisearlier StackOverflow page.

使用双括号中的另一种方法是显示在较早的StackOverflow页。

回答by helpermethod

No, but something similar:

不,但类似的东西:

LinkedList<String> linkedList = new LinkedList<String>(Arrays.asList("String1", "String2", "String3", "String4", ...));

回答by Colin

No not in the way you gave an example of.

不,不是你举的例子的方式。

You can pass a Collection however.

但是,您可以传递 Collection。

See http://download.oracle.com/javase/1.5.0/docs/api/java/util/LinkedList.html

请参阅http://download.oracle.com/javase/1.5.0/docs/api/java/util/LinkedList.html

回答by tonio

I usually use Arrays.asList("String1", "String2")for that purpose.

我通常Arrays.asList("String1", "String2")用于这个目的。

If you need to add elements to the list afterwards, use

如果之后需要将元素添加到列表中,请使用

List<String> ll = new ArrayList<String>(Arrays.asList("String1", "String2"));

This will give you a list that can be extended.

这将为您提供一个可以扩展的列表。

回答by Chuck

I prefers option like this:

我更喜欢这样的选择:

static final List<Integer> nums = new LinkedList<Integer>() {{
add(1);
add(2);
add(3); }};

And no matter what time of list.

而且无论什么时候的名单。