1

I have a LinkedList:

Linkedlist<String> m = new Linkedlist<String>();

and it contains:

m = {"apple", "banana", "pineapple", "orange", "mango"};

My current code is:

string s = "";
for(int i = 0; i < m.size(); i++)
{
 s += a.get(i);
 s += a.get(i);
 s += a.get(i);
 return s;
}

What I expect:

[apple] or [banana, orange] or [apple, pineapple, mango].

But my result is always:

[apple, apple, apple]

What must I do to get the expected output?

Socrates
9,68429 gold badges71 silver badges118 bronze badges
asked Apr 24, 2017 at 3:59
12
  • what exactly is the question? Commented Apr 24, 2017 at 4:02
  • Thanks, pbd , this is my first time to ask question. I just want to know how to use loop to loop over the linked list and use compound additive operator to show the result I wanted. Commented Apr 24, 2017 at 4:07
  • @Pbd OP probably meant LinkedList, and this is probably Java, but you should probably ask first before editing the question like that without being sure. Editing a post to change class names is something one should almost never do. Commented Apr 24, 2017 at 4:07
  • @Dukeling, sorry about my mistake. It is a java question. Commented Apr 24, 2017 at 4:09
  • 1
    If you get [apple, apple, apple] with a foreach loop, my guess is that the linked-list contains only apple 3 times, or you just took the first element each time. You might want to construct and post a Minimal, Complete, and Verifiable example that shows the problem you're having. Commented Apr 24, 2017 at 4:23

1 Answer 1

1

You can output List in different ways.

1) First is closest to your code

LinkedList<String> m = new LinkedList<String>();
m.add("apple");
m.add("banana");
m.add("pineapple");
m.add("orange");
m.add("mango");
StringBuilder s = new StringBuilder();
for(String value : m)
 s.append(value);
System.out.println(s);

Output is (perhaps you would like to format it a bit)

applebananapineappleorangemango

2) Easiest way, in my opinion, is to connect StringUtils from apache.

System.out.println(StringUtils.join(m, ", "));

Output

apple, banana, pineapple, orange, mango

3) If you need it just for debug, you can simple use toString() from list. So

System.out.println(m.toString());

gives you

[apple, banana, pineapple, orange, mango]
answered Apr 24, 2017 at 5:51

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.