码迷,mamicode.com
首页 > 其他好文 > 详细

hashCode和identityHashCode的区别

时间:2014-09-12 17:18:03      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:object   对象   java   hashcode   

I、 hashCode()方法是Object类下面的一个方法,供继承类重写,根据对象内存地址计算哈希值,

    String类重写了hashCode方法,并改为根据字符序列来计算哈希值

III、identityHashCode()方法是System类中的静态方法,根据对象内存地址来计算哈希值;

方法示例:

public static void main(String[] args)

     {

         //下面程序中s1和s2是两个不同对象

         String s1 = newString("Hello");

         String s2 =newString("Hello");    

        //String类重写了Object类的hashCode方法——改为根据字符序列计算hashCode值,

        //因为s1和s2的字符序列相同,所以它们的hashCode方法返回值相同

         System.out.println(s1.hashCode() +"----" + s2.hashCode());      

 

        //s1和s2是不同的字符串对象,所以它们的identityHashCode值不同,

       //identityHashCode是根据对象的地址计算得到的,所以任何两个不同的对象的           

        //identityHashCode值总是不相等

        System.out.println(System.identityHashCode(s1)+ "----" 

                            +System.identityHashCode(s2));

 

        //s3和s4是相同的字符串对象,所以它们的identityHashCode值相同

        String s3 ="Java";

        String s4 ="Java";

       System.out.println(System.identityHashCode(s3)+"----" 

                           +System.identityHashCode(s4));}

输出:

69609650----69609650

13078969----3154093

28399250----28399250

hashCode和identityHashCode的区别

标签:object   对象   java   hashcode   

原文地址:http://blog.csdn.net/liuxiaoxiaosmile/article/details/39230763

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!