Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HashMap.containsValue - What's the point?

Tags:

java

hashmap

I've got a HashMap and I need to fetch an item by its integer value. I notice there's a containsValue() function, but it would appear I still have to iterate through the map to find the correct index anyway.

My question is; why use containsValue() if I'm required to traverse it afterwards?

Also, am I missing the point completely? ;-)

like image 606
Frederik Avatar asked Mar 29 '10 13:03

Frederik


2 Answers

A map maps a key to a value. If you have a value and you know the map contains this value, why do you need the key anymore?

On the other hand, if you really need the key or you have just a property of the value, you can iterate the entrySet(), check the value and return the key if found:

for (Map.Entry<Index,Value> entry : map.entrySet()) {
  if (entry.getValue().getXy().equals(xy)) {
    return entry.getKey();
  }
}
like image 187
Arne Burmeister Avatar answered Oct 01 '22 15:10

Arne Burmeister


I think Map.containsValue is a mistake in the design of the Map interface.

One very occasionally encounters Map implementations that provide a faster-than-linear implementation of containsValue. For example, a map might internally represent each distinct value as a small integer and then use bit patterns to represent sets of values. Such a map might be able to detect in constant time that it had never seen a given value before (though it might still take linear time to return an affirmative result).

However, an operation that sometimes takes linear time and sometimes takes constant time is not a useful foundation for a generic algorithm. You can't substitute a LinkedList for an ArrayList and expect things to work well, even though they both support random access in their API. A client that needs a constant-time containsValue must maintain a separate HashSet of values to be assured of good performance. Clients happy with linear-time performance can just write the loop themselves.

Even if the maintainers of the Map interface also regret adding containsValue, it is of course impossible for them to remove it now.

like image 29
Alan A Donovan Avatar answered Oct 01 '22 16:10

Alan A Donovan