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

后端 未结 11 2363
攒了一身酷
攒了一身酷 2021-01-03 14:09

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

 public static ArrayList error = new ArrayList<>();

for (int x= 1         


        
相关标签:
11条回答
  • 2021-01-03 14:51

    The brackets you see are just an automatic way to display a List in JAVA (when using System.out.println(list); for example.

    If you do not want them to show when showing it, you can create a custom method :

    public void showList(List<Integer> listInt)
    {
        for(int el : listInt)
        {
            System.out.print(el + ", ");
        }
    }
    

    Then adjust this code to show this according to your liking !

    0 讨论(0)
  • 2021-01-03 14:54

    brackets is not a part of your array list, since as you've mentioned it's Integer typed

    ArrayList<Integer>

    when you print errors using

    System.out.println(errors);
    

    it's just formatting your data, just iterate over the array and print each value separately

    0 讨论(0)
  • 2021-01-03 14:56

    This is an ArrayList of Integer. This ArrayList can not contain a character like '['. But you can remove an Integer from it like this -

    error.remove(3);
    
    0 讨论(0)
  • 2021-01-03 14:57

    The brackets are not actually within the list it's just a representation of the list. If any object goes into a String output the objects toString() method gets called. In case of ArrayList this method delivers the content of the list wrapped by this brackets.

    If you want to print your ArrayList without brackets just iterate over it and print it.

    0 讨论(0)
  • 2021-01-03 14:58

    Short answer: System.out.println(errors.toString().substring(1, errors.toString().length() - 1))

    Explanation: when you call System.out.println(obj) with an Object as a parameter, the printed text will be the result of obj.toString(). ArrayList.toString() is implemented in a way that makes it represent its content between brackets [] in a comma separated concatenation of each of the contained items (their .toString() representation as well).

    It is not a good practice to rely on another class's toString() implementation. You should use your own way to format your result.

    0 讨论(0)
提交回复
热议问题