==
equals()
方法是等价于==
的
public class Test {
public static void main(String[] args) {
String a = "hello";
String b = "hello";
String c = new String("hello");
//在java中字符串的值是不可改变的,相同的字符串在堆内存中只会存一份,所以a和b指向的是同一个对象;
System.out.println(a==b);//true
//a和c在堆内存中的地址不同(c是新开辟的),所以a和b指向的不是同一个对象;
System.out.println(a==c);//false
//这里的equals等价于==,因为a和b地址相同
System.out.println(a.equals(b));//true
//这里equals比较后两个不同的对象,但结果确实true
//说明Strung重写过了equals方法
System.out.println(a.equals(c));//true
//ab为同一个对象,应该拥有相同的hashcode,但c为另一个对象,hashchode应该不同
//说明String重写了hashcode
System.out.println(a.hashCode());
System.out.println(b.hashCode());
System.out.println(c.hashCode());
}
}
可以看出在String类中对euqals()方法和hashcode方法进行了重写
相同的对象,应该拥有相同的地址和hashcode,因此在判断两个对象是否相同时需要同时重写hashcode,和equals方法
参考资料hashcode详解 - 有梦想的老王 - 博客园 (cnblogs.com)
原文:https://www.cnblogs.com/Sheltonz/p/14101868.html