Key for customizing HashMap and customizing HashMap
If you use a custom type as the key of HashMap, you must reload hashCode () and equals () at the same time to find the custom key in HashMap.
For example, the custom Point class:
public class Point { private int x; private int y; public Point(int x,int y) { this.x = x; this.y = y; } public void setX(int x) { this.x = x; } public int getX() { return x; } public void setY(int y) { this.y = y; } public int getY() { return y; } @Override public String toString() { return "["+x+","+y+"]"; }}
View Code
Example:
Clusters data example: <String, Set <Point> <user, coordinate list of all cluster centers>
Point as the Map key:
Map <Point, Set <String> usersOfCertainPoint = new LinkedHashMap <Point, Set <String> (); // <grid coordinate, list of all users whose cluster center is the coordinate> Iterator <Map. entry <String, Set <Point> iterator = clusters. entrySet (). iterator (); while (iterator. hasNext () {Map. entry <String, Set <Point> entry = iterator. next (); for (Point p: entry. getValue () {if (! UsersOfCertainPoint. containsKey (p) {// Set <String> userSet = new HashSet <String> (); userSet. add (entry. getKey (); usersOfCertainPoint. put (p, userSet);} else {usersOfCertainPoint. get (p ). add (entry. getKey ());}}}
View Code
Error output example:
The problem is that the Point automatically inherits from the base class Object. Therefore, the hashCode () method of the Object is used to generate a hash code. By default, the hash code is calculated using the Object address. Therefore, even two Point objects with the same value, such as [4515,-8198], have different hash codes because of their different addresses.
If you only need to overload hashCode () and still cannot run normally, you must also overload the equals () method. In HashMap, the comparison sequence of keys is as follows:
Reload hashCode () and equals ():
@ Override public boolean equals (Object o) {if (this = o) // whether it is a reference of this class return true; if (! (O instanceof Point) return false; Point p = (Point) o; return (p. x = this. x) & (p. y = this. y) ;}@ Override public int hashCode () {int result = 17; result = 31 * result + x; result = 31 * result + y; return result ;}
View Code
Correct output example: