关于System.identityHashCode(obj) 与 obj.hashcode()

看官方提供的API , 对System.identityHashCode()的解释为 :

identityHashCode

public static int identityHashCode(Object x)
返回给定对象的哈希码,该代码与默认的方法 hashCode() 返回的代码一样,无论给定对象的类是否重写 hashCode()。null 引用的哈希码为 0。 
可是真的是这样吗???



让我们做下面的测试:
 1 public class Main {
2 public static void main(String[] argv) throws Exception {
3 // File file1 = new File("a");
4 // File file2 = new File("a");
5 // File file3 = new File("b");
6
7 String file1 = "abc";
8 String file2 = "abc";
9 String file3 = "abcdef";
10
11
12 int hc1 = file1.hashCode();
13 System.out.println(hc1);
14 int hc2 = file2.hashCode();
15 System.out.println(hc2);
16 int hc3 = file3.hashCode();
17 System.out.println(hc3);
18
19 int ihc1 = System.identityHashCode(file1);
20 System.out.println(ihc1);
21 int ihc2 = System.identityHashCode(file2);
22 System.out.println(ihc2);
23 int ihc3 = System.identityHashCode(file3);
24 System.out.println(ihc3);
25 }
26 }
不管注释掉File类 还是 String 类, 运行后的结果都是:  hashcode() 与 System.identityHashCode() 生成的数字并不相等~~ 
重新把File类或 String 类换成 Object 时, hashcode() 与 System.identityHashCode() 生成的数字才是相等的 .
暂时还还早不到其中的原因,  向各位兄台讨教~

转载于:https://www.cnblogs.com/danne823/archive/2011/11/29/about_hashcode.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值