覆盖类中的equals()和hashCode()方法
class MyClass { private String name;/**时代Java公众号 - N o w J a v a . c o m**/ public MyClass(String name) { this.name = name; } /* Re-implement the equals() method */ public boolean equals(Object otherObject) { // Are they the same? if (this == otherObject) { return true; } // Is otherObject a null reference? if (otherObject == null) {//nowjava return false; } // Do they belong to the same class? if (this.getClass() != otherObject.getClass()) { return false; } // Get the reference of otherObject is a SmartCat variable MyClass otherCat = (MyClass) otherObject; // Do they have the same names boolean isSameName = (this.name == null ? otherCat.name == null : this.name .equals(otherCat.name)); return isSameName; }