I have a collection arraylist in Java.
For example when I do:
test is the collection.
System.out.println(test.getTester());
Why do I get the result of: [jamesbond]
I only want jamesbond but why do they give me the [ ] too?
I have a collection arraylist in Java.
For example when I do:
test is the collection.
System.out.println(test.getTester());
Why do I get the result of: [jamesbond]
I only want jamesbond but why do they give me the [ ] too?
From your question, assuming that you have ArrayList of Strings as the collection (since it's printing [jamesbond]).
When you write test.getTester()
, the java calls the toString() method on the collection and it'll print elements between [
and ]
with separated by comma.
You can use iterator over the collection to print the individual elements.
List<String> stringColl = Arrays.asList("jamesbond","danielocean");
// Java 8
stringColl.forEach(stringElem -> System.out.println(stringElem));
// Java 7 or below
for(String stringElem : stringColl){
System.out.println(stringElem);
}
Let a String help you with that and use the replace method...
// if your list doesnt contain any element with the chars [ or ]
String listNoBrackets = l.toString().replace("[", "").replace("]", "");
System.out.println(listNoBrackets);
// if your list contains at least 1 element with the chars [ or ]
String listWithBrackets = l.toString().substring(1, l.toString().length() - 1);
System.out.println(listWithBrackets);
Just remove the first and last character with substring method.
String foo = test.getTester().toString();
System.out.println(foo.substring(1, foo.length() - 1);
Note: If you try to print an array with more than one object, you will see that the brackets are always the first and last character, the elements themselves are sperated with commas.