2

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,423
  • 1
  • 32
  • 43
munmunbb
  • 297
  • 9
  • 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,426
  • 6
  • 53
  • 75
epoch
  • 16,396
  • 4
  • 43
  • 71
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,426
  • 6
  • 53
  • 75
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,957
  • 2
  • 20
  • 36