40 likes | 212 Views
equals 和 hashcode. Use == to determine if two reference variables refer to the same object. Use equals() to determine if two objects are meaningfully equivalent. If x.equals (y) is true, then x.hashCode () == y.hashCode () is true . If you override equals(), override hashCode ().
E N D
equals 和 hashcode Use == to determine if two reference variables refer to the same object.Use equals() to determine if two objects are meaningfully equivalent.If x.equals(y) is true, then x.hashCode() == y.hashCode() is true.If you override equals(), override hashCode().
equals 和 hashcode public class MainClass { public static void main(String[] argv) { MyClassmyClass = new MyClass(); MainClassmainClass = new MainClass(); System.out.println(myClass.equals(mainClass)); } } class MyClass { public booleanequals(Object object) { if (object instanceofMyClass == false) { return false; } return true; } }
equals 和 hashcode 1. If two objects are equal according to the equals(Object) method, then calling the hashCode() method on each of the two objects must produce the same integer result.2. If two objects are unequal according to the equals(Object) method, there's no requirement about hashcode().3. If calling hashcode() on two objects produce different integer result, then both of themmust be unequal according to the equals(Object).
Hashcode /equals • Example 0 • Example 1 • Example 2 • Example 3 • Example 4