//手動的實現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; }