1

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?

LinkedList<String> s = new LinkedList<>();
s = {"a"->"b"->"c"->"d"};

Thanks!

scrappedcola
  • 10,199
  • 1
  • 29
  • 41
munmunbb
  • 267
  • 7
  • 22

3 Answers3

5

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");
Anubian Noob
  • 13,166
  • 6
  • 49
  • 73
epoch
  • 16,149
  • 3
  • 42
  • 69
5

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.

Community
  • 1
  • 1
Anubian Noob
  • 13,166
  • 6
  • 49
  • 73
2

You could do this:

LinkedList<String> linkedList = new LinkedList<String>();
    linkedList.add("a");
    linkedList.add("b");
    linkedList.add("c");
    linkedList.add("d");
Sandeep Kaul
  • 2,769
  • 2
  • 18
  • 34