Java uses a custom type as the HashMap key

Source: Internet
Author: User

?? 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:

    1. Calculates the hashcode of an object to see if it exists in the table
    2. 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

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.