HashMap.containsValue - What's the point?

前端 未结 7 751
臣服心动
臣服心动 2021-01-04 13:16

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 m

相关标签:
7条回答
  • 2021-01-04 14:01

    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.

    0 讨论(0)
提交回复
热议问题