This is a fairly simple question. When you print out a LinkedList, like so:
System.out.println(list);
It prints it out, surrounding the list in square brackets like this:
[thing 1, thing 2, thing 3]
Is there a way I can print it out without the square brackets?
replaceAll("(^\\[|\\]$)", ""); In the above code first we are removing first square bracket then we are removing the second square bracket and replacing i with empty string. Now the output string has array list with no square brackets. If you have any doubt or suggestions then leave it in comment box.
Print LinkedList using a for loop Just as with other Lists, a Linked List starts from index 0 , and we can use the size() method to get the total number of elements in the List. For each iteration of the for loop, pass the index to the get(index) method, which will return the element in the specific address.
Yes - iterate the list and print it (with comma after each, but the last element). However, there are utils to help:
Guava:
String result = Joiner.on(", ").join(list);
commons-lang:
String result = StringUtils.join(list, ", ");
And one note: don't rely on the .toString()
method of any object. It is not meant for displaying the object to users, or to be used as a predefined format - it is meant mainly for debugging purposes.
A quick-and-dirty answer is:
String s = list.toString();
System.out.println(s.substring(1, s.length()-1));
You could subclass LinkedList
and override it's toString()
method, but that seems a little excessive. Instead, iterate over it's elements and construct a String
with either a StringBuilder
, or a StringBuffer
(if concurrency is an issue).
Note:
I suggest you don't follow the answer provided by @Sean Owen, since that's implementation-dependent and therefore, fragile.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With