我正在尝试使用 Java HashMap<String, object>
as and object dictionary so 按名称查找对象 ( string
)。所有的名字都是独一无二的;但是,通常非常相似(例如:“delay1”、“delay2”)。 HashMap.get(string)
保证找到具有该名称的唯一项目,或者只是寻找具有相同哈希值的项目。
代码运行的方式,看起来查找不一致。
如果HashMap<String, object>
不能满足我的需要,Java 中是否有类似于 C# 字典的功能?
最佳答案
是的,HashMap
保证找到完全匹配的匹配项,而不仅仅是具有相同哈希码的匹配项。
基于哈希的容器通过在查找键和来自其哈希桶之一的候选对象上调用 equals()
来实现这一点,以确保存在实际匹配。这就是必须始终覆盖 equals
和 hashCode
方法的原因,如 documentation 中所述。 :
Note that it is generally necessary to override the
hashCode
method whenever this [equals
] method is overridden, so as to maintain the general contract for thehashCode
method, which states that equal objects must have equal hash codes.
关于java - 使用 HashMap 查找对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33830633/