Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use a third party Class Object as Hashmap Key?

Tags:

java

oop

hashmap

OK I understand the working of equals and hashcode and How they are used in hashmap. But This question crossed my mind What if I am having a third party object which does'nt have overridden hashcode and equals and I am not even allowed to modify it.

Consider following Class:

//Unmodifiable class
public final class WannaBeKey{

    private String id;

    private String keyName;

    //Can be many more fields

    public String getId()
    {
          return id;
    }

    public String getKeyName()
    {
          return id;
    }
    //no hashcode or equals :(

  }

Now I want to make this class as my Hashmap key obviously it won't work without equals and hashcode. I want to know is there any way to handle such cases? I am unable to think of any or I am way over my head..

Thanks.

like image 862
Dangling Piyush Avatar asked Aug 07 '14 14:08

Dangling Piyush


People also ask

Can we use class object as key in HashMap?

We can conclude that to use a custom class for a key, it is necessary that hashCode() and equals() are implemented correctly. To put it simply, we have to ensure that the hashCode() method returns: the same value for the object as long as the state doesn't change (Internal Consistency)

Can an object be a Map key?

The Map object holds key-value pairs and remembers the original insertion order of the keys. Any value (both objects and primitive values) may be used as either a key or a value.

Can we use object as key?

The short answer is "no". All JavaScript object keys are strings. Even if you pass an object as a key, the object's toString() will be called on it, and the key will be stringified to [object Object] .

Which two methods you need to implement to use an object as key in HashMap?

In order to use any object as Key in HashMap, it must implements equals and hashcode method in Java.


2 Answers

I've encountered this previously, and worked around it by creating a wrapper for the WannaBeKey as such:

public class WannaBeKeyWrapper {

  private final WannaBeKey key;


  public WannaBeKeyWrapper(WannaBeKey key) {
    this.key = key;
  } 

  public boolean equals(Object obj) {

    // Insert equality based on WannaBeKey
  }

  public int hashCode() {
    // Insert custom hashcode in accordance with http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#hashCode()
  }
}

Obviously this changes your Set from Set<WannaBeKey> to Set<WannaBeKeyWrapper>, but you should be able to account for that.

like image 108
Jason Nichols Avatar answered Sep 28 '22 16:09

Jason Nichols


You can create a wrapper for that object which will have the overridden methods. Then you can use the wrapper class as the key of your hash map.

like image 28
Bhesh Gurung Avatar answered Sep 28 '22 16:09

Bhesh Gurung