如何检查地图中的密钥而不管情况如何?

编程入门 行业动态 更新时间:2024-10-08 08:28:03
本文介绍了如何检查地图中的密钥而不管情况如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想知道HashMap中是否存在特定的键,所以我使用的是containsKey(key)方法。但它区分大小写,即如果有一个带有Name的键并且我正在搜索名称,则它不会返回true。那么有什么方法我可以知道而不用打扰钥匙的情况吗?

I want to know whether a particular key is present in a HashMap, so i am using containsKey(key) method. But it is case sensitive ie it does not returns true if there is a key with Name and i am searching for name. So is there any way i can know without bothering the case of the key?

谢谢

推荐答案

不是传统地图。

abc是来自ABC的不同字符串,它们的哈希码是不同的,它们的equals()方法将是相对于彼此返回false。

"abc" is a distinct string from "ABC", their hashcodes are different and their equals() methods will return false with respect to each other.

最简单的解决方案是在插入/检查之前简单地将所有输入转换为大写(或小写)。您甚至可以编写自己的 Map 包装器,以确保一致性。

The simplest solution is to simply convert all inputs to uppercase (or lowercase) before inserting/checking. You could even write your own Map wrapper that would do this to ensure consistency.

如果您想维护如果提供了密钥的大小写,但是通过不区分大小写的比较,您可以考虑使用 TreeMap 并提供自己的比较器,它将不区分大小写。但是,在走下这条路线之前要认真思考,因为 最终会出现一些不可调和的不一致 - 如果有人打电话给 map.put(abc,1)然后 map.put(ABC,2),地图中存储的密钥是​​什么情况?你能说得有意义吗?你是否觉得如果有人用你的地图包装你的地图,例如 HashMap 你会丢失功能吗?或者,如果有人碰巧正在迭代你的密钥集,并使用 equals()进行自己的快速包含检查,你会得到不一致的结果吗?还会有很多其他类似的案例。 请注意,您违反了地图合同(因为密钥相等是根据键上的equals()方法定义)所以它在任何意义上都是不可行的。

If you want to maintain the case of the key as provided, but with case-insensitive comparison, you could look into using a TreeMap and supplying your own Comparator that will compare case-insensitively. However, think hard before going down this route as you will end up with some irreconcilable inconsistencies - if someone calls map.put("abc", 1) then map.put("ABC", 2), what case is the key stored in the map? Can you even make this make sense? Are you comfortable with the fact that if someone wraps your map in a standard e.g. HashMap you'll lose functionality? Or that if someone happens to be iterating through your keyset anyway, and does their own quick "contains" check by using equals() you'll get inconsistent results? There will be lots of other cases like this too. Note that you're violating the contract of Map by doing this (as key equality is defined in terms of the equals() method on the keys) so it's really not workable in any sense.

维护严格的大写地图 更易于使用和维护,并且具有实际上是合法地图实施的优势。

Maintaining a strict uppercase map is much easier to work with and maintain, and has the advantage of actually being a legal Map implementation.

更多推荐

如何检查地图中的密钥而不管情况如何?

本文发布于:2023-11-23 07:04:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1620543.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:密钥   图中   情况

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!