Olaf Bergin
Olaf Bergin

Reputation: 63

insert duplicate keys to hash map

I have created hash map and when I debug it I saw that I have duplicte keys. I didnt override the hashCode() & equals(Object obj) in the key - Object1 and i wonder how will it affect the performance of the map search?

private HashMap<Object1,Object2> map = new HashMap<Object1,Object2>();

Upvotes: 0

Views: 1276

Answers (4)

user1917885
user1917885

Reputation:

You cannot have duplicate keys but you can have duplicate values. Might be you got confused with the key and value.

Upvotes: 0

Hunter McMillen
Hunter McMillen

Reputation: 61550

It is not possible to have duplicate keys in a Map, you have different keys that "appear" the same (Maybe based on their toString()? )because you have not overridden equals() and hashCode(), but in reality the keys are different.

This means that in order to get all values from your Map you need to keep every key you created and store it somewhere, which to me defeats the purpose of the Map.

Summary:

Override equals() and hashCode(), then put your key/value pairs into the Map.

Upvotes: 4

UmNyobe
UmNyobe

Reputation: 22920

How can you have duplicate keys? You didn't override equals() neither hashcode() so you cannot say "duplicated objects", because that's exactly the purpose of theses methods. You probably debug and saw different values, but for the JVM they are not equals based on the default Object.equals() and Object.hashcode() (well actually the closest superclass)

Upvotes: 0

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382464

It won't really give you bad performances (more the opposite) but it will prevent your objects from being seen as duplicate.

If you want each instance to be seen as a different key, don't override the equals and hashCode methods. But that means you'll need exactly the same instance to retrieve your value in the map.

If you want to retrieve the value with a different instance (for example with the same id), then you need to override the methods.

But the problem isn't really a performance one.

Upvotes: 0

Related Questions