使用示例
public class Test {
public static void main(String[] args) {
// 打印:[3, 1, 2, 5, 4, 6, 5, 9]
System.out.println(Arrays.toString(new int[] {3, 1, 2, 5, 4, 6, 5, 9}));
// 打印:[[1, 2], [3], [3, 2, 5, 8]]
System.out.println(Arrays.deepToString(new int[][] {{1, 2}, {3, 4}, {3, 2}}));
}
}
Arrays.toString方法源码分析
/**
* Arrays.toString方法源码(以整型数组来分析,其他同理)
*/
public static String toString(int[] 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(a[i]);
if (i == iMax)
return b.append(']').toString();
b.append(", ");
}
}
- 可以看出,Arrays.toString方法实现非常简单:
- 构造一个StringBuilder对象
- 对数组进行循环,并拼接数组中的元素到StringBuilder对象中
- 返回组装成功的字符串
Arrays.deepToString方法源码分析
/**
* Arrays.deepToString方法源码
*/
public static String deepToString(Object[] a) {
if (a == null)
return "null";
int bufLen = 20 * a.length;
if (a.length != 0 && bufLen <= 0)
bufLen = Integer.MAX_VALUE;
StringBuilder buf = new StringBuilder(bufLen);
deepToString(a, buf, new HashSet<Object[]>());
return buf.toString();
}
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方法会稍微复杂一点点:
- 同样也是构造一个StringBuilder对象
- 然后遍历一维数组中的每个元素
- 判断每个是否为数组(不是数组则直接记录对象的toString字符串描述)
- 否则,校验元素数组的对象类型
- 若为基本类型数据,则直接调用toString方法,并记录其结果
- 否则,再嵌套调用deepToString方法
- 返回拼接成功后的字符串