//手动的实现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; }
对Equals()方法的重写
时间: 2024-10-06 00:13:01