Object.hashCode()方法与System.identityHashCode(object)的区别
2014-06-26 10:06
423 查看
String a = new String("hhh");
String b = new String("hhh");
System.out.println(System.identityHashCode(a));
System.out.println(System.identityHashCode(b));
System.out.println(a.hashCode());
System.out.println(b.hashCode());
打印结果
前两个不同
后两个相同
这是为什么呢,我们知道目前a和b是两个不同的对象,他们在内存中存放的地址是不同的,System.identityHashCode方法是java根据对象在内存中的地址算出来的一个数值,不同的地址算出来的结果是不一样的。因此这里打印出的结果不一样。
doc上如是说:返回给定对象的哈希码,该代码与默认的方法 hashCode() 返回的代码一样,无论给定对象的类是否重写 hashCode()。
但是为什么后两个相同呢?这是因为,String类中已经重新写了hashCode()方法,也就是说,String类中hashcode,已经不是根据对象在内存中的地址计算出来的。(具体怎么算出来的,我还没有研究),就是说即使对象在内存中的地址不一样,String中hashcode也可能一样
String b = new String("hhh");
System.out.println(System.identityHashCode(a));
System.out.println(System.identityHashCode(b));
System.out.println(a.hashCode());
System.out.println(b.hashCode());
打印结果
前两个不同
后两个相同
这是为什么呢,我们知道目前a和b是两个不同的对象,他们在内存中存放的地址是不同的,System.identityHashCode方法是java根据对象在内存中的地址算出来的一个数值,不同的地址算出来的结果是不一样的。因此这里打印出的结果不一样。
doc上如是说:返回给定对象的哈希码,该代码与默认的方法 hashCode() 返回的代码一样,无论给定对象的类是否重写 hashCode()。
但是为什么后两个相同呢?这是因为,String类中已经重新写了hashCode()方法,也就是说,String类中hashcode,已经不是根据对象在内存中的地址计算出来的。(具体怎么算出来的,我还没有研究),就是说即使对象在内存中的地址不一样,String中hashcode也可能一样
相关文章推荐
- 关于System.identityHashCode() 与 obj.hashcode()
- 关于System.identityHashCode(obj) 与 obj.hashcode()
- hashCode和identityHashCode的区别
- System.identityHashCode(Object o)
- hashCode和identityHashCode的区别
- hashCode和identityHashCode的区别
- hashCode和identityHashCode的区别你知道吗?
- hashCode和identityHashCode的区别
- hashCode和identityHashCode的区别
- JDK源码学习--System.identityHashCode(Object)
- 关于System.identityHashCode(obj) 与 obj.hashcode()
- hashCode和identityHashCode的区别
- hashCode和identityHashCode的区别
- System.identityhashcode()
- hashCode和identityHashCode底层是怎么生成的
- hashCode和identityHashCode的关系
- JAVA Object对象(toString、equals、hashCode方法)、String类、StringBuffer、StringBuider、System、Runtime、Date、Mat
- Java语言中Object对象的hashCode()取值的底层算法是怎样实现的?,object hashcode
- Java学习之equals()、hashCode()、identityHashCode()、toString()和==
- 比较Java中"hashCode" "equals" "==" "System.identityhashcode"