equals()和hashCode()隐式调用时的约定

package com.hash;

import java.util.HashMap;

public class Apple {  
    private String color;  
   
    public Apple(String color) {  
        this.color = color;  
    }  
   
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((color == null) ? 0 : color.hashCode());
        return result;
    }

    public boolean equals(Object obj) {  
        if (!(obj instanceof Apple))  
            return false;      
        if (obj == this)  
            return true;  
        return this.color == ((Apple) obj).color;  
    } 
   
    public static void main(String[] args) {  
        Apple a1 = new Apple("green");  
        Apple a2 = new Apple("red");  
   
        //hashMap stores apple type and its quantity  
        HashMap<Apple, Integer> m = new HashMap<Apple, Integer>();  
        m.put(a1, 10);  
        m.put(a2, 20);  
        System.out.println(m.get(new Apple("green")));  
    }  
} 

从上文代码不难看出,HashMap已保存一个"green"的Apple对象,但是,,在执行时,会发生一个问题,,,用map获取"Apple"对象时,并未找到。

然而,为什么会造成这问题呢,,,这就是本文主旨所在。

---是由于hashCode()引起,因为没有重写hashCode()方法.
equals()方法与hashCode()方法的隐式调用时的约定是:
1.如果两个对象相等(equals),那么他们必须拥有相同的哈希吗(hashCode)
2.即使两个对象拥有相同的hashCode,他们也不一定相等.
Map的核心思想就是可以比线性查找更快. 通过散列值(hash)作为键(key)来定位对象的过程分为两步:
在Map内部,存储着一个顶层数组,顶层数组的每个元素指向其他的数组,查找或存储的时候,先根据key对象的hashCode()值计算出数组的索引,然后到这个索引找到所指向的第二层线性数组,使用equals方法来比较是否有相应的值(以返回或者存储).
Object类中的hashCode()默认为每个对象返回不同的int值,因此在上面的例子中,两个相等(equal)的对象,返回了不同的hashCode值.
解决方法是为此类添加hashCode方法,比如,使用color字符串的长度作为示范:
public int hashCode(){  
    // 此种实现,要求 color值定以后就不得修改  
    // 否则同一个物理对象,前后有两个不同的hashCode,逻辑上就是错的。  
    return this.color.length();   
} 

参考地址:http://www.acfun.tv/a/ac1876770

原文地址:https://www.cnblogs.com/james-roger/p/5916078.html