先揭晓答案:重写这俩个方法是为了在使用HashMap 传入自定义Key时,HashMap还能根据需求正常使用。
现在有这样的需求:根据Key的属性返回value。
不重写会怎样,来看代码
class Key{
int i;
Key(int i){
this.i=i;
}
}
public class DefineKey {
public static void main(String[] args) {
// TODO Auto-generated method stub
Key key1=new Key(1);
Key key2=new Key(1);
HashMap<Key,Integer> map=new HashMap<>();
map.put(key1, 1);
System.out.println(map.get(key2));
}
}
//执行结果 为 null
那么只重写HashCode()呢?
import java.util.HashMap;
class Key{
Integer i;
Key(int i){
this.i=i;
}
@Override
public int hashCode() {
// TODO Auto-generated method stub
return i.hashCode();
}
}
public class DefineKey {
public static void main(String[] args) {
// TODO Auto-generated method stub
Key key1=new Key(1);
Key key2=new Key(1);
HashMap<Key,Integer> map=new HashMap<>();
map.put(key1, 1);
System.out.println(map.get(key2));
}
}
// 还是null, 虽然 get(key2) 找到了 key1所在桶 但父类的equal方法对于俩个对象还是不等的
重写俩个方法呢??
class Key{
Integer i;
Key(int i){
this.i=i;
}
@Override
public int hashCode() {
// TODO Auto-generated method stub
return i.hashCode();
}
@Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
Key key=(Key)obj;
return this.i==key.i;
}
}
public class DefineKey {
public static void main(String[] args) {
// TODO Auto-generated method stub
Key key1=new Key(1);
Key key2=new Key(1);
HashMap<Key,Integer> map=new HashMap<>();
map.put(key1, 1);
System.out.println(map.get(key2));
}
}
这样的话 就返回 1 了