How to use a third-party class object as a Hashmap key?

OK. I understand how equals and hashcode work and how they are used in hashmap. But this question crossed my mind. What if I have a third-party object that has no overridden hashcode and is equal, and I’m not even allowed to modify it.

Consider the 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, it is obvious that it will not work without peers and hashcode. I want to know if there is a way to deal with such cases? I can’t think of anything, or I am above my head.

Thanks.

+6
source share
4 answers

I came across this earlier and worked around it, creating a wrapper for 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 aware of this.

+8
source

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

+4
source

You can wrap the actual object in another instance with the necessary semantics:

 class KeyWrapper { WannaBeKey key; // constructor omitted @Override public int hashCode() { return key.getId().hashCode(); } @Override public boolean equals(Object o) { // equals method implementation } } 

Alternatively, you can simply extend the class (if the class was not final , as you indicated in your edit).

+1
source

This question has already been given completely, but I thought it was worth mentioning that the above solutions are part of a specific design pattern known as Decorator .

The Adapter or Wrapper template uses essentially the same solution, but is designed to convert code to a different interface, while Decorator is used for extension.

+1
source

Source: https://habr.com/ru/post/973495/


All Articles