hashcode override

    //20190524
        //recipeName null
    //recipeName duplicate
        @Override 
        public boolean equals(Object obj) { 
            if (this == obj) { 
                return true; 
            } 
            if (obj == null) { 
                return false; 
            } 
            if (getClass() != obj.getClass()) { 
                return false; 
            } 
            
            Recipe other = (Recipe) obj;

            
            if (recipeName == null) { 
                if (other.recipeName != null) { 
                    return false; 
                } 
            } 
            else if (!recipeName.equals(other.recipeName)) { 
                return false; 
            } 
            
            return true; 
        } 
        
        
        
        @Override 
        public int hashCode() { 
            final int prime = 31; 
            int result = 1;  
            result = prime * result + ((recipeName == null) ? 0 : recipeName.hashCode()); 
            return result; 
        } 
        //20190524

hashCode 在自定义类时要重载方法

这里的final int prime = 31为何要选这个值呢,有以下几个原因:
1.首先31是个质数,只能被1和本身整除的数,乘上后不容易出现重复
2.其次31这个数不大也不小,不至于超出返回类型的int,也不容易在乘上后重复
3.最后就是31=32-1=2^5 -1,计算方便,向左移动5位,再减一就行了

https://blog.csdn.net/dyc_dyc/article/details/81636094
https://blog.csdn.net/li123128/article/details/88996462

你可能感兴趣的:(hashcode override)