Java的HashCode

·HashCode就是根据对象存储在内存的地址计算出的一个值。这个值可以标识这个对象的位置。也可以对比两个引用变量是否指向同一个对象。
·String重写了hashCode方法——改为根据字符序列计算hashCode值,所以String通过String new("String")方式创建的两个相同字符串内容的对象他们的hashcode相同。
·要想获取正确的hashcode,需要使用System.identityHashCode() 方法


例子:摘自某书籍

public class IdentityHashCodeTest
{
	public static void main(String[] args) 
	{
		//下面程序中s1和s2是两个不同对象
		String s1 = new String("Hello");
		String s2 = new String("Hello");
		//String重写了hashCode方法——改为根据字符序列计算hashCode值,
		//因为s1和s2的字符序列相同,所以它们的hashCode方法返回值相同
		System.out.println(s1.hashCode() 
			+ "----" + s2.hashCode());
		//s1和s2是不同的字符串对象,所以它们的identityHashCode值不同
		System.out.println(System.identityHashCode(s1) 
			+ "----" + System.identityHashCode(s2));
		String s3 = "Java";
		String s4 = "Java";
		//s3和s4是相同的字符串对象,所以它们的identityHashCode值相同
		System.out.println(System.identityHashCode(s3)
			+ "----" + System.identityHashCode(s4));
	}
}


输出结果:

69609650----69609650
13078969----3154093
28399250----28399250

原文地址:https://www.cnblogs.com/keanuyaoo/p/3306271.html