對Equals()方法的重寫

//手動的實現equals()方法
//    重寫Object類的equals(Object obj)方法,保證兩個對象若屬性值完全相等,則返回true
    public boolean equals(Object obj){
        if(this==obj){
            return true;
        }else if(obj instanceof Person){
            Person p=(Person)obj;
            return this.getId()==p.getId()&&this.getAge()==p.getAge()&&this.getName().equals(p.getName());
        }else 
            return false;
    }
    @Override
   public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
           return false;
        }
        if (!(obj instanceof Person)) {
            return false;
        }
       Person other = (Person) obj;
        if (age != other.age) {
            return false;
        }
        if (id != other.id) {
            return false;
        }
        if (name == null) {
            if (other.name != null) {
                return false;
            }
        } else if (!name.equals(other.name)) {
            return false;
        }
       return true;
    }

String類中對Equals()的重寫爲:

  public boolean equals(Object anObject) {
        if (this == anObject) {
            return true;
        }
        if (anObject instanceof String) {
            String anotherString = (String)anObject;
            int n = value.length;
            if (n == anotherString.value.length) {
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = 0;
                while (n-- != 0) {
                    if (v1[i] != v2[i])
                        return false;
                    i++;
                }
                return true;
            }
        }
        return false;
    }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章