当一个Java类没有重写hashCode()方法时,打印这个类的实例会得到一个不错而且独特的数字。
Object类的Javadoc对hashCode()进行了说明:
尽量合理地说,由Object类定义的hashCode方法返回的是不同对象的不同整数。
但是当该类重写hashCode()方法后,如何获取它的唯一编号?
当一个Java类没有重写hashCode()方法时,打印这个类的实例会得到一个不错而且独特的数字。
Object类的Javadoc对hashCode()进行了说明:
尽量合理地说,由Object类定义的hashCode方法返回的是不同对象的不同整数。
但是当该类重写hashCode()方法后,如何获取它的唯一编号?
hashCode()和identityHashCode()返回值之间存在差异。对于两个不相等的对象o1和o2(使用==测试),它们的hashCode()可能相同。请参见下面的示例,了解这是如何发生的。
class SeeDifferences
{
public static void main(String[] args)
{
String s1 = "stackoverflow";
String s2 = new String("stackoverflow");
String s3 = "stackoverflow";
System.out.println(s1.hashCode());
System.out.println(s2.hashCode());
System.out.println(s3.hashCode());
System.out.println(System.identityHashCode(s1));
System.out.println(System.identityHashCode(s2));
System.out.println(System.identityHashCode(s3));
if (s1 == s2)
{
System.out.println("s1 and s2 equal");
}
else
{
System.out.println("s1 and s2 not equal");
}
if (s1 == s3)
{
System.out.println("s1 and s3 equal");
}
else
{
System.out.println("s1 and s3 not equal");
}
}
}