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

后端 未结 11 2452
攒了一身酷
攒了一身酷 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:45

    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 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 );
    

提交回复
热议问题