Java 容器Set,HashMap, ArrayList 之toString()差异原因

最近使用Set, HashMap, 数组三类容器的时候,发现它们的toString()打印出来的数据有些差异,

看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. 其二, 外面分方括号,大括号,是怎么打印出来的,这个还需要进一步验证.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值