This question already has an answer here:
这个问题在这里已有答案:
- Initialization of an ArrayList in one line 30 answers
在一行30中初始化ArrayList的答案
I would like to write a linked list like this:
我想写一个像这样的链表:
"a" -> "b" -> "c" -> "d"
This is what I've tried so far but it's obviously wrong. I was wondering how to express this correctly in java?
这是我到目前为止所尝试过的,但显然是错误的。我想知道如何在java中正确表达这一点?
LinkedList<String> s = new LinkedList<>();
s = {"a"->"b"->"c"->"d"};
Thanks!
3 个解决方案
#1
That's how the pointers in the list look internally, to actually add
it to the list you need to do this:
这就是列表中指针在内部的外观,实际上将它添加到您需要执行此操作的列表中:
List<String> s = new LinkedList<>();
s.add("a");
s.add("b");
s.add("c");
s.add("d");
#2
Take a look at this answer.
看看这个答案。
LinkedList<String> list = new LinkedList<>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
If you really want it on one line:
如果你真的想要它在一条线上:
LinkedList<String> list = new LinkedList<>(Arrays.asList("a","b","c","d"));
Though that does have a performance overhead.
虽然这确实有性能开销。
#3
You could do this:
你可以这样做:
LinkedList<String> linkedList = new LinkedList<String>();
linkedList.add("a");
linkedList.add("b");
linkedList.add("c");
linkedList.add("d");
#1
That's how the pointers in the list look internally, to actually add
it to the list you need to do this:
这就是列表中指针在内部的外观,实际上将它添加到您需要执行此操作的列表中:
List<String> s = new LinkedList<>();
s.add("a");
s.add("b");
s.add("c");
s.add("d");
#2
Take a look at this answer.
看看这个答案。
LinkedList<String> list = new LinkedList<>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
If you really want it on one line:
如果你真的想要它在一条线上:
LinkedList<String> list = new LinkedList<>(Arrays.asList("a","b","c","d"));
Though that does have a performance overhead.
虽然这确实有性能开销。
#3
You could do this:
你可以这样做:
LinkedList<String> linkedList = new LinkedList<String>();
linkedList.add("a");
linkedList.add("b");
linkedList.add("c");
linkedList.add("d");