Object的hashCode()默认是返回内存地址的,但是hashCode()可以重写,所以hashCode()不能代表内存地址的不同
System.identityHashCode(Object)方法可以返回对象的内存地址,不管该对象的类是否重写了hashCode()方法。
下面来验证:
public class TestMem { public static void main(String[] args) { String s1 = "hello"; String s2 = "world"; String s3 = "helloworld"; String s4 = s1+s2; System.out.println(s3==s4); System.out.println(s3.hashCode()); System.out.println(s4.hashCode()); System.out.println(System.identityHashCode(s3)); System.out.println(System.identityHashCode(s4)); } }
结果
false - -
s3和s4的hashCode一样,但是内存地址不一样。
由此可知,要想获取对象的内存地址应使用System.identityHashCode()方法
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/207859.html原文链接:https://javaforall.net
