用自定义类作为key,必须重写equals()和hashCode()方法。
自定义类中的equals() 和 hashCode()都继承自Object类。
Object类的hashCode()方法返回这个对象存储的内存地址的编号。
而equals()比较的是内存地址是否相等。
- public boolean equals(Object obj){
- return (this == obj);
- }
在Map,set等容器中,在存取时都需要大量的equals操作,会影响效率。所以引入了hashCode()。
通过hashCode()能够计算出一个hash值,通过hash值来判断两个对象的值是否相等,如果hash值不相等则说明这两个对象不相等,如果hash值相等则继续用equals()去判断两个对象是否相等。
编写一个高效率,高准确率的hashCode可能会比较困难。
示例:
- class IntPair{
- private int i1;
- private int i2;
- public IntPair(int i1, int i2){
- this.i1 = i1;
- this.i2 = i2;
- }
- public boolean equals(Object obj){
- if(this == obj)//判断是否是本类的一个引用
- return true;
- if(obj == null)//
- return false;
- IntPair pair = (IntPair)obj;
- if(this.i1 != pair.i1)
- return false;
- if(this.i2 != pair.i2)
- return false;
- return true;
- }
- public int hashCode(){
- int result = 17;
- result = result * 31 + i1;
- result = result * 31 + i2;
- return result;
- }
- }