I have created an Array List in Java that looks something like this:
public static ArrayList<Integer> error = new ArrayList<>(); for (int x= 1; x<10; x++) { errors.add(x); }
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:
This method calls at first String.valueOf(x) to get the printed object's string value
The brackets are added by the toString
implementation of ArrayList. To remove them, you have to first get the String:
String errorDisplay = errors.toString();
and then strip the brackets, something like this:
errorDisplay = errorDisplay.substring(1, errorDisplay.length() - 1);
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:
List<Integer> errors = new ArrayList<>(); StringBuilder sb = new StringBuilder(); for (int x = 1; x<10; x++) { errors.add(x); sb.append(x).append(","); } sb.setLength(sb.length() - 1); String errorDisplay = sb.toString();
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():
// create a new array with the same size as the list Integer[] errorsArray = new Integer[errors.size()]; // fill the array errors.toArray(errorsArray );
EDIT: From an object-oriented perspective one could argue that errors and errorsDisplay conceptually belong together in a class, e.g:
public class Errors { private final List<Integer> codes = new ArrayList<>(); public void add(int error) { codes.add(error); } public Stream<Integer> get() { return codes.stream(); } @Override public String toString() { return codes.stream() .map(Object::toString) .collect(Collectors.joining(", ")); } }