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

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

    There are not brackets inside your list. This is just the way Java prints a list by default.

    If you want to print the content of your list, you can something like this

    for (Integer error : errors) {
        System.out.format("%d ", error);
    }
    
    0 讨论(0)
  • 2021-01-03 14:41

    You can write like this.

    String output = errors.toString().replaceAll("(^\\[|\\]$)", "");

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

    If you print your error list, it will internally call the toString() method of your list and this method add the brackets. There are a few possibilities. You can get the String via toString() method an remove the brackets from the String. Or you write your own method to print the List.

    public static <T> void printList(List<T> list)
    {
        StringBuilder output = new StringBuilder();
        for(T element : list)
            output.append(element + ", ");
        System.out.println(output);
    }
    
    0 讨论(0)
  • 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<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 );
    
    0 讨论(0)
  • 2021-01-03 14:46
    String text = errors.toString().replace("[", "").replace("]", "");//remove brackets([) convert it to string
    
    0 讨论(0)
  • 2021-01-03 14:49

    System.out.println(error.toString().substring(1, error.toString().length()-1)); This worked for me

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