Skip to content
Advertisement

How to remove the brackets [ ] from ArrayList#toString()?

I have created an Array List in Java that looks something like this:

JavaScript

When I print errors I get it errors as

[1,2,3,4,5,6,7,8,9]

Now I want to remove the brackets([ ]) from this array list. I thought I could use the method errors.remove(“[“), but then I discovered that it is just boolean and displays a true or false. Could somebody suggest how can I achieve this?

Thank you in advance for your help.

Advertisement

Answer

You are probably calling System.out.println to print the list. The JavaDoc says:

JavaScript

The brackets are added by the toString implementation of ArrayList. To remove them, you have to first get the String:

JavaScript

and then strip the brackets, something like this:

JavaScript

It is not good practice to depend on a toString() implementation. toString() is intended only to generate a human readable representation for logging or debugging purposes. So it is better to build the String yourself whilst iterating:

JavaScript

Note that this is not an array, just a String displaying the contents of the list. To create an array from a list you can use list.toArray():

JavaScript

EDIT: From an object-oriented perspective one could argue that errors and errorsDisplay conceptually belong together in a class, e.g:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement