HashMap.containsValue - What#39;s the point?(HashMap.containsValue - 有什么意义?)
问题描述
我有一个 HashMap,我需要通过它的整数值来获取一个项目.我注意到有一个 containsValue() 函数,但看来我仍然必须遍历地图才能找到正确的索引.
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.
我的问题是;如果我之后需要遍历它,为什么还要使用 containsValue()?
My question is; why use containsValue() if I'm required to traverse it afterwards?
另外,我是否完全错过了重点?;-)
Also, am I missing the point completely? ;-)
推荐答案
映射将键映射到值.如果你有一个值并且你知道地图包含这个值,为什么你还需要这个键?
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?
另一方面,如果你真的需要key或者你只有value的一个属性,你可以迭代entrySet()
,检查value,如果找到就返回key:
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();
}
}
这篇关于HashMap.containsValue - 有什么意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:HashMap.containsValue - 有什么意义?


- Jersey REST 客户端:发布多部分数据 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01