编辑:现在正确地解释了问题。
我有一个 HashMap ,我想在其中存储一起看到的单词集(键)和一起看到它们的行(值)。这是我想出的结构:
HashMap<HashSet<String>, HashSet<Integer>> hm= ...
对于输入:
芒果、香蕉、苹果
苹果、香蕉
桃子、海象
海象,桃子
当我逐行阅读本文时,我根据行中的单词组合创建了新的临时键(哈希集尚未插入 HashMap 中)。每个临时键都是行中单词子集的哈希集。如果临时 key 已经存在于我的 HashMap 中,我通过检查
if(hashmap.containsKey(hashset))
我只是将新行添加到该键的对应值,如果没有,我会在 HashMap 中创建一个新条目并处理它。
我绝不会更改现有 key 。我只在 hasmmap 中更新它们对应的值。
我的 HashMap ,在读取文件结束时,应该看起来像这样
[苹果,香蕉]=[1,2]
[桃子,海象]=[3,4]
...
问题是
if(hashmap.containsKey(hashset))
一段代码并不总能检测到现有的 key 。为什么是这样?这种结构不允许吗?
谢谢
最佳答案
这应该可行,但您需要注意键的可变性。如果你改变了其中一个键的内容,它的哈希码就会改变,你的 map 就会开始做奇怪的事情。来自 Map
的 javadoc :
Note: great care must be exercised if mutable objects are used as map keys. The behavior of a map is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is a key in the map. A special case of this prohibition is that it is not permissible for a map to contain itself as a key. While it is permissible for a map to contain itself as a value, extreme caution is advised: the equals and hashCode methods are no longer well defined on such a map.
为避免这种情况,在创建时立即使用 Collections.unmodifiableSet()
包装 key ,或者只使用 ImmutableSet
来自 Guava 。
关于java - 我可以将 HashSet 作为 HashMap 中的键吗?如果没有,建议替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9773846/