首先我们要明白我们为什么重写equals和hashcode..
equals()方法作用当然就是帮助我们判断某个对象与本对象是否相等啦.
使用==判断的只是两个对象的地址值是否相等而已,但我们在日常使用中,对于某些类来说,我们需要的可能是这个类的属性相等时,我们就认为两个对象就是相等.怎么做呢,就是去重写equals方法了,
但为什么要同时重写hashcode方法呢?
hashCode()返回的就是一个hash码,相等的对象必须具有相等的hash码.如果不等会有什么结果.写个例子
public class Dog {
private String name;
public Dog(String name) {
this.name = name;
}
public static void main(String[] args) {
String str1 = new String("a");
String str2 = new String("a");
HashMap<String, String> map1 = new HashMap<>();
map1.put(str1,"value");
System.out.println("str1.equals(str2):"+str1.equals(str2));
System.out.println("key为str1时,value为"+map1.get(str1));
System.out.println("key为str2时,value为:"+map1.get(str2));
//-------------------------------------------------------
System.out.println("--------------");
Dog Dog1 = new Dog("a");
Dog Dog2 = new Dog("a");
HashMap<Dog, String> map2 = new HashMap<>();
map2.put(Dog1,"value");
System.out.println("Dog1.equals(Dog2):"+Dog1.equals(Dog2));
System.out.println("key为Dog1时,value为"+map2.get(Dog1));
System.out.println("key为Dog2时,value为"+map2.get(Dog2));
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Dog dog = (Dog) o;
return Objects.equals(name, dog.name);
}
/*@Override
public int hashCode() {
return Objects.hash(name);
}*/
}
阅读上面代码:我们可以看到当把Dog对象作为hashMap中key值时,dog1和dog2相等,按理说我们取hashMap中的值时,使用dog1或者dog2时都能得到相同的value.但实际并未有.如果重写了hashCode方法.就是我们想要的结果.就是取到相同的值.