Key for customizing HashMap and customizing HashMap

Source: Internet
Author: User

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:

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.