1. hashCode1.1 Basic Concepts
Hashcode is an int number (the hash value of an object) that is calculated by the JDK based on the address of the object, representing the storage location of the object in memory.
The Hashcode () method is a method provided by the Super Class object class, which can be overridden by all classes.
1.2 Why override the Equals () method to override the Hashcode () method
Hashcode () Equality is a necessary non-sufficient condition for the equality of two objects.
Equals () equality is a sufficient and necessary condition for the equality of two objects.
Overriding the Equals () method is necessary to rewrite the Hashcode () method to improve efficiency , initially by Hashcode () to determine equality, equality, and then by the other way in Equals () to determine whether equality
2. Equals () method
To ensure program robustness, the following conditions must be met when overriding the Equals method:
- Reflexivity: A.equals (A) to return True
- Symmetry: If A.equals (B) returns True, B.equals (A) also returns true
- Transitivity: If A.equals (b) is True,b.equals (c) True, then A.equals (c) is also true, equivalent to a = B, b = c, then A = C
- Consistency: A.equals (b) must always return true whenever the state of A and B objects does not change
- A.equals (NULL) to return FALSE
3. Practice
Designing a class person containing height, weight, age, and Blood is an integer attribute, implements the Hashcode method, orchestrates four attributes into an integer as Hashcode () and Equals () method
1 Public classPerson {2 Public intheight;3 Public intweight;4 Public intAge ;5 Public intBlood;6 7 Public intgetheight () {8 returnheight;9 }Ten One Public voidSetHeight (intheight) { A This. Height =height; - } - the Public intgetweight () { - returnweight; - } - + Public voidSetweight (intweight) { - This. Weight =weight; + } A at Public intGetage () { - returnAge ; - } - - Public voidSetage (intAge ) { - This. Age =Age ; in } - to Public intGetblood () { + returnBlood; - } the * Public voidSetblood (intblood) { $ This. Blood =Blood;Panax Notoginseng } - the PublicPerson (intHeightintWeightintAgeintblood) { + This. Height =height; A This. Weight =weight; the This. Age =Age ; + This. Blood =Blood; - } $ $ @Override - Public Booleanequals (Object o) { - the if( This. hashcode () = =O.hashcode ()) { - return true;Wuyi } the return false; - } Wu - @Override About Public inthashcode () { $ - inti = (height << & 0xff) | (Weight << & 0xff) | (Age << 8 & 0xff) |Blood; - - returni; A } + the Public Static voidMain (string[] args) { -person P1 =NewPerson (1, 2, 3, 5); $person P2 =NewPerson (1, 3, 3, 4); the System.out.println (P1.equals (p2)); the } the the}
Java rewrite hashcode () and Equals () methods