Using an instance of an object as a key in hashmap, and then access it with exactly new object?(使用对象的实例作为 hashmap 中的键,然后使用全新的对象访问它?)
问题描述
我有一个带有键对象的 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 中的键,然后使用全新的对象访问它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用对象的实例作为 hashmap 中的键,然后使用全


基础教程推荐
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 降序排序:Java Map 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01