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 - 有什么意义?


基础教程推荐
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 从 python 访问 JVM 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01