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 Objects will only be equal if they are in fact the same object).
Effective Java - 所有对象通用的方法
这篇关于使用对象的实例作为 hashmap 中的键,然后使用全新的对象访问它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用对象的实例作为 hashmap 中的键,然后使用全
基础教程推荐
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 多个组件的复杂布局 2022-01-01
- Java Swing计时器未清除 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 从 python 访问 JVM 2022-01-01
