问题描述
我有一个带有键对象的 hasmap,
I have a hasmap with a key object,
HashMap<Key, Object> test;
并将新密钥(相同")作为密钥..
and make new Key("the same") as key..
所以它就像..:
test.put(new Key("the same"), someObject);
(不将该键存储在变量中)
(without storing that key in a variable)
所以.. 过了一会儿...我想访问哈希图,因为我没有对象,所以我尝试制作 new Key("the same") 并将其作为键.但是没用.
so.. after a while... i want to access the hashmap, because i do not have the object, i've tried to make new Key("the same") and make it as a key. But it didnt work.
如何让它工作?(不将第一个对象键"保存在变量中)
How to make it work? (without saving the first object "key" in a variable)
因此,目前,我使用 String 对象作为键.
So meanwhile, for now, im using String object as a key.
HashMap<String, Object>
推荐答案
需要在Key
上实现hashCode
和equals
.默认实现这些方法只是检查 instance 是否相等(换句话说,两个 Object
只有当它们实际上是同一个对象时才会相等).
You need to implement hashCode
and equals
on Key
. The default implementation of these methods simply checks for instance equality (in other words, two Object
s will only be equal if they are in fact the same object).
Effective Java - 所有对象通用的方法
这篇关于使用对象的实例作为 hashmap 中的键,然后使用全新的对象访问它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!