2015年9月18日 星期五

物件的比較


物件的比較,原則上必須 Override Object 物件內的 equals() 方法:
public class Employee {
    
    private int empId;
    private String name;
    private String ssn;
    private double salary;

    public Employee(int empId, String name, String ssn, double salary) {
        this.empId = empId;
        this.name = name;
        this.ssn = ssn;
        this.salary = salary;
    }

    @Override
    public boolean equals(Object obj) {
        boolean result = false;
        
        if ((obj != null) && (obj instanceof Employee)){
            Employee e = (Employee)obj;
            if ((e.empId == this.empId) &&
                    (e.name.equals(this.name)) &&
                    (e.ssn.equals(this.ssn)) &&
                    (e.salary == this.salary)){
                    result = true;
            }
        }
        
        return result; 
    }

   //......請參考這一篇程式內容......

}

測試用程式:
public class Demo {
    public static void main(String[] args){
           
        Employee e = new Employee(101, "Jim Smith", "011-12-2345", 100_000.00);
        Employee m = new Manager(102, "Joan Kern", "012-23-4567",110_450.54, "Marketing");
        Employee es = e;
        Employee es2 = new Employee(101, "Jim Smith", "011-12-2345", 100_000.00);
        
        if ( e ==  es ){
            System.out.println("1.同一物件");
        }
        
        if ( e.equals(es)){
            System.out.println("1.物件內容相同");
        }
        
        if ( e ==  es2 ){
            System.out.println("2.同一物件");
        }
        
        if ( e.equals(es2)){
            System.out.println("2.物件內容相同");
        }
        
        if ( e ==  m ){
            System.out.println("3.同一物件");
        }
        
        if ( e.equals(m)){
            System.out.println("3.物件內容相同");
        }
    }
}