?? You need to override the Hashcode () and Equals () methods to implement a custom key lookup in HashMap.
public class PhoneNumber{ private int prefix; //区号 private int phoneNumber; //电话号 public PhoneNumber(int prefix, int phoneNumber) { this.prefix = prefix; this.phoneNumber = phoneNumber; }}
import java.util.HashMap;public class Test1{ public static void main(String[] args) { HashMap<PhoneNumber, String> map = new HashMap<>(); map.put(new PhoneNumber(027, 12345678), "zhangsan"); map.put(new PhoneNumber(027, 22222222), "lisi"); map.put(new PhoneNumber(027, 33333333), "wangwu"); map.put(new PhoneNumber(027, 33333333), "abc"); System.out.println(map.toString()); System.out.println(map.get(new PhoneNumber(027, 12345678))); System.out.println(map.get(new PhoneNumber(027, 22222222))); System.out.println(map.get(new PhoneNumber(027, 33333333))); }}
The result of the operation is:
{[email protected]=zhangsan, [email protected]=wangwu, [email protected]=lisi, [email Protected]=ABC}
Null
Null
Null
From there, we can see that there are two problems:
- New PhoneNumber (027, 33333333) This key was added two times, but in HashMap WANGWU and ABC exist simultaneously.
- The value obtained by using the Get method is null
The correct approach is to modify the PhoneNumber class directly, overriding the Equals and Hashcode methods, and modifying the PhoneNumber class as follows:
public class PhoneNumber{ private int prefix; //区号 private int phoneNumber; //电话号 public PhoneNumber(int prefix, int phoneNumber) { this.prefix = prefix; this.phoneNumber = phoneNumber; } @Override public boolean equals(Object o) { if(this == o) { return true; } if(!(o instanceof PhoneNumber)) { return false; } PhoneNumber pn = (PhoneNumber)o; return pn.prefix == prefix && pn.phoneNumber == phoneNumber; } @Override public int hashCode() { int result = 17; result = 31 * result + prefix; result = 31 * result + phoneNumber; return result; }}
Re-execute the above function with the result:
{[email protected]=abc, [email protected]=zhangsan, [email protected]=lisi}
Zhangsan
Lisi
Abc
As you can see, the previous errors have been corrected.
In HashMap, the comparison order of lookup keys is:
- Calculates the hashcode of an object to see if it exists in the table
- Checks if the object in the hashcode position is equal to the current object
The above method of calculating hashcode is mentioned in effective Java 9th:
- For each key field F in the object, computes the hash code C of the int type for the field,result = * result + C
Java uses a custom type as the HashMap key