Arrays.toString()与Arrays.deepToString()都是将数组实例化输出。
区别在于 输出的深度不同,以下是Arrays.toString()的源码:
public static String toString(Object[] a) {
if (a == null)
return "null";
int iMax = a.length - 1;
if (iMax == -1)
return "[]";
StringBuilder b = new StringBuilder();
b.append('[');
for (int i = 0; ; i++) {
b.append(String.valueOf(a[i]));
if (i == iMax)
return b.append(']').toString();
b.append(", ");
}
}
Arrays.toString()通过循环,使用StringBuilder将数组中每个元素遍历出来后用 “,” 分割,且用 “[” “]” 包裹。
以下是Arrays.deepToString()源代码:
private static void deepToString(Object[] a, StringBuilder buf,
Set<Object[]> dejaVu) {
if (a == null) {
buf.append("null");
return;
}
int iMax = a.length - 1;
if (iMax == -1) {
buf.append("[]");
return;
}
dejaVu.add(a);
buf.append('[');
for (int i = 0; ; i++) {
Object element = a[i];
if (element == null) {
buf.append("null");
} else {
Class<?> eClass = element.getClass();
if (eClass.isArray()) {
if (eClass == byte[].class)
buf.append(toString((byte[]) element));
else if (eClass == short[].class)
buf.append(toString((short[]) element));
else if (eClass == int[].class)
buf.append(toString((int[]) element));
else if (eClass == long[].class)
buf.append(toString((long[]) element));
else if (eClass == char[].class)
buf.append(toString((char[]) element));
else if (eClass == float[].class)
buf.append(toString((float[]) element));
else if (eClass == double[].class)
buf.append(toString((double[]) element));
else if (eClass == boolean[].class)
buf.append(toString((boolean[]) element));
else { // element is an array of object references
if (dejaVu.contains(element))
buf.append("[...]");
else
deepToString((Object[])element, buf, dejaVu);
}
} else { // element is non-null and not an array
buf.append(element.toString());
}
}
if (i == iMax)
break;
buf.append(", ");
}
buf.append(']');
dejaVu.remove(a);
}
Arrays.deepToString()中采用了递归,如果元素是数组,递归遍历一次。遍历每一层直到元素不为数组。
通过两个实例测试:
public static void main(String[] args) {
String[] str = {"a","b","c"};
System.out.println(Arrays.toString(str));
System.out.println(Arrays.deepToString(str));
}
输出结果:
[a, b, c]
[a, b, c]
对于一维数组,输出相同,都是遍历一次后得到最小的元素为String就输出。
public static void main(String[] args) {
String[][] str = {{"a","b","c"},{"d","e","f"},{"g","h","i"}};
System.out.println(Arrays.toString(str));
System.out.println(Arrays.deepToString(str));
}
输出结果:
[[Ljava.lang.String;@1540e19d, [Ljava.lang.String;@677327b6, [Ljava.lang.String;@14ae5a5]
[[a, b, c], [d, e, f], [g, h, i]]
Arrays.toString()因为只遍历一次,遍历出的元素为直接打印字符串数组,
Arrays.deepToString()通过递归,遍历了二维数组的每个元素