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!

0

3 Answers 3

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");
Sign up to request clarification or add additional context in comments.

2 Comments

@downvoter, care to explain?
Misclick, I mean to upvote it. Sorry about that :P.
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.

Comments

2

You could do this:

LinkedList<String> linkedList = new LinkedList<String>();
    linkedList.add("a");
    linkedList.add("b");
    linkedList.add("c");
    linkedList.add("d");

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.