Java如何将数组转换为字符串

从 Java 1.5 开始,我们可以获得指定数组内容的字符串表示,而无需迭代其每个元素。
只需将 Arrays.toString(Object[]) 或者 Arrays.deepToString(Object[]) 用于多维数组:

int[] arr = {1, 2, 3, 4, 5};
System.out.println(Arrays.toString(arr));     //[1, 2, 3, 4, 5]
int[][] arr = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};
System.out.println(Arrays.deepToString(arr)); //[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Arrays.toString() 方法使用 Object.toString() 方法生成数组中每一项的 String 值,除了原始类型数组,它可以用于所有类型的数组。
例如:

public class Cat { /* implicitly extends Object */
        @Override
         public String toString() {
                 return "CAT!";
          }
}
Cat[] arr = { new Cat(), new Cat() };
System.out.println(Arrays.toString(arr)); //[CAT!, CAT!]

如果该类不存在重写的 toString(),则将使用从 Object 继承的 toString()。
通常输出不是很有用,例如:

public class Dog {
    /* implicitly extends Object */
}
Dog[] arr = { new Dog() };
System.out.println(Arrays.toString(arr));    
日期:2020-06-02 22:15:15 来源:oir作者:oir