Java当中我们常用的一可能是String.HashCode这个方法所产生或是我们自己来覆盖超类当中的HashCode方法,等等的操作,但是System.identityHashCode当中的方法是根据当前对象的地址来计算的,就算是两个对象是相同的(不是引用)他们两个的HashCode值也是不同的;
下面是例子:

  1. package com.barneyx.args;

  2. /**
  3.  * Created by Administrator on 2017/2/11.
  4.  */
  5. public class IdentityHashCodeTest {
  6.     public static void main(String[] args) {
  7.         //这里是两个对象,两个不同的地址,所以肯定HashCode的值是不同的
  8.         String s1 = new String("hello");
  9.         String s2 = new String("hello");

  10.         System.out.println(
  11.                 s1.hashCode()+
  12.                         "---------------"+
  13.                         s2.hashCode()
  14.         );
  15.         
  16.         System.out.println(System.identityHashCode(s1)+"-----"+System.identityHashCode(s2));

  17.         String s3 = "Java";
  18.         String s4 = "Java";
  19.         
  20.         //s3和s4是相同的字符串所以他们只有一分引用,所以他们的HashCode是相同的
  21.         System.out.println(System.identityHashCode(s3)+"-----------"+System.identityHashCode(s4));


  22.     }
  23. }

  24. /******************************
  25. 运行结果:
  26. 99162322---------------99162322
  27. 460141958-----1163157884
  28. 1956725890-----------1956725890

  29. Process finished with exit code 0
  30. *******************************/

11-08 09:54
查看更多