HashMap.containsValue - 有什么意义? [英] HashMap.containsValue - What's the point?

查看:21
本文介绍了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 - 有什么意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆