5-2 equals ,hashCode

package fivetwo;

public class Employee{
    private String str;
    private int x;
    
    /*
     * equal的原则:
     * 自反性:对于任何非空的 x.equals(x)返回true
     * 对称性:对于任何x,y   x.equals(y)的结果与y.equals(x)相等
     * 传递性:对于任何x,y,z  x.equals(y)为true,y.equals(z)为true,x.equals(z)为true
     * 一致性:x和y的对象没有方法改变 x.equals(y)值不变
     * x为非空,equal(null) 返回为false
     */
    
    public static void main(String[] args) {
        Employee newEmployee =  new    Employee();
        newEmployee.method1();
    }
    
    public boolean equals(Object otherObject){
        
        if (this == otherObject) {
            return true;
        }
        if (otherObject == null) {
            return false;
        }
        if (!(getClass() == otherObject.getClass())) {
            return false;
        }
        
        Employee other= (Employee)otherObject;
//        return (this.x == other.x && this.str.equals(other.str));
        return (this.x == other.x && ObjectExtend.equals(this.str, other.str));
    }
    

    
    /*
     * 散列码 has code
     * 定义:对象导出的整型值,散列码是没有规律的。
     * 
     * String的hasCode算法是31*i+char[j]
     * int的hasCode : 值本身
     * 
     * StringBuffer 没有hashCode方法,导出的对象储存地址
     */
    public void method1(){
//        System.out.println(this.str.hashCode()); 
//        Employee newEmployee =  new    Employee();
//        System.out.println(newEmployee.hashCode());  
        System.out.println(new Integer(6).hashCode());  
    }
    
    public int hashCode(){
//        return ObjectExtend.hasCodes(this.str)+
//                    new Integer(x).hashCode();
        return ObjectExtend.hash(this.str,this.x);
    }
    
}
package fivetwo;

public class Manager extends Employee{

    private int bonus;
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Manager m1 = new Manager();
        Manager m2 = new Manager();
//        m1.equals(m2);
        
        //
        Employee e1 = new Employee();
        System.out.println(m1 instanceof Employee); 
        System.out.println(e1 instanceof Manager); 
        
    }
    
    //子类的比较先调用超类的equal方法,超类的域不相等就不可能相等
    public boolean equals(Object otherObject){
        if (!super.equals(otherObject)) {
            return false;
        }
        
        Manager other = (Manager)otherObject;
        return this.bonus == other.bonus;
    }
    

}
package fivetwo;

import java.util.Arrays;

public class ObjectExtend extends Object{

    public static void main(String[] args) {
    }
    
    
    //Objects.equals jdk的高版本非空判断
    public static boolean equals(Object a,Object b){
        return a==b || (a!=null && a.equals(b));  
    }
    public static int hasCodes(Object o){
        return o != null?o.hashCode():0;
    }
    
    public static int hash(Object... o){
        return Arrays.hashCode(o); 
    }
}

 

posted @ 2018-01-02 13:15  aLa神灯  阅读(105)  评论(0编辑  收藏  举报