-1

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?

Nicky
  • 63
  • 1
  • 2
  • 11
  • 2
    Because the toString() method of the object returned by test.getTester() prints the object that way. You didn't post the relevant code, so it's hard to say, but it's probably a List or a Set. Post the relevant code. – JB Nizet Apr 30 '16 at 09:09
  • 2
    The more interesting question is: why do you want to remove the brackets? If you want to print the list, you can iterate over it and print each item yourself instead of using the `toString()` function... – Rick Apr 30 '16 at 09:11
  • Note that test is not the collection. Collections don't have any getTester() method. Post the relevant code. – JB Nizet Apr 30 '16 at 09:19

3 Answers3

2

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);
    }
Rolson Quadras
  • 446
  • 3
  • 8
0

Let a String help you with that and use the replace method...

Example:

// 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);
Community
  • 1
  • 1
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
0

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.

Maljam
  • 6,244
  • 3
  • 17
  • 30
Lasse Meyer
  • 1,429
  • 18
  • 38