简体   繁体   中英

HashMap using Object as key

I made a post a few days ago about using a HashMap in a simple banking program, but I'm having issues with using Objects as keys.

    HashMap <Account,Client> HM = new HashMap<Account, Client>();
    HM.put(new Account(2193,"Uri"), new Client(2193,0,"Uri"));
    HM.get(2193,"Uri");

Account and Client are classes in other parts of the source. My issue is that the HM.get isn't working as intended, and is giving me an error. Is there another way I'm to 'get' the value? Not sure how to use the key. Do note, the setup of the HashMap is without error.

Furthermore, is there a better way to go about this?

This will give you better idea. that why you need to override hashcode and equals method.

Why do I need to override the equals and hashCode methods in Java?

After overriding hashcode and equals method.

you need to use your object while getting data from hashMap.

HM.get(new Account(2193,"Uri"));

First of all this code does not compile as you are passing 2 arguments to get() which expects only 1 argument.

That argument is supposed to be the key you use in the map and has to be of the same type you declared while declaring your map, in your case HashMap <Account,Client> HM means that HM (which btw should be lowercase by convention) holds as keys objects of type Account and objects of type Client as values.

It would still compile if you did:

get(2193)

Since get() takes an Object but it would simply return a null .

You need to do get(new Account(2193,"Uri")) .

Next you do not need to override equals and hashCode in those classes but it is highly recommended (others already pointed to links saying why). Also as per the doc you should make the keys immutable so they do not change, otherwise you might get strange behavior.

Note: great care must be exercised if mutable objects are used as map keys. The behavior of a map is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is a key in the map. A special case of this prohibition is that it is not permissible for a map to contain itself as a key. While it is permissible for a map to contain itself as a value, extreme caution is advised: the equals and hashCode methods are no longer well defined on such a map.

For more detailed description of the Map interface follow Oracle's tutorial

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM