Reputation: 111
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?
Upvotes: 1
Views: 573
Reputation: 186
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]
Upvotes: 1