您的位置:首页 > 其它

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

2011-11-29 15:05 447 查看
看官方提供的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() 生成的数字才是相等的 .暂时还还早不到其中的原因, 向各位兄台讨教~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: