最近使用Set, HashMap, 数组三类容器的时候,发现它们的toString()打印出来的数据有些差异,
}
而, int数组中没有对toString()进行重写, 依然用的是Object对象中的toString()函数, 其具体实现如下:
所以打印出来的就是,你看到的效果(tempSet = [I@75b84c92)
2. 其二, 外面分方括号,大括号,是怎么打印出来的,这个还需要进一步验证.
看Demo:
public class myClass { public static void main(String[] args){ Set tempSet = new HashSet(); tempSet.add("AAA"); tempSet.add("BBB"); tempSet.add("CCC"); System.out.println("tempSet = "+tempSet.toString()); Map tempMap = new HashMap(); tempMap.put("1","111"); tempMap.put("2","222"); tempMap.put("3","333"); System.out.println("tempSet = "+tempMap.toString()); int[] tempInt = new int[]{1,2,3,4}; System.out.println("tempSet = "+tempInt.toString()); } }
输出:
tempSet = [AAA, CCC, BBB]
tempSet = {1=111, 2=222, 3=333}
tempSet = [I@75b84c92
Process finished with exit code 0
从输出可以看出, HashSet, HashMap 对象通过调用toString()方法直接打印出了存储的值, 而数组则直接打印出来数组的地址, 这之间的差异是什么呢?
1. 参看了HashSet的源码,其内部是用HashMap 实现的, 在HashMap源码中重写了toString(), 具体核心代码如下:
public class HashMap<K, V> extends AbstractMap<K, V> implements Map<K, V>, Cloneable, Serializable { ....
static class Node<K, V> implements Entry<K, V> {
.... public final String toString() { return this.key + "=" + this.value; }}
}
而, int数组中没有对toString()进行重写, 依然用的是Object对象中的toString()函数, 其具体实现如下:
public class Object { ....
public String toString() { return this.getClass().getName() + "@" + Integer.toHexString(this.hashCode()); } ....}
所以打印出来的就是,你看到的效果(tempSet = [I@75b84c92)
2. 其二, 外面分方括号,大括号,是怎么打印出来的,这个还需要进一步验证.