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
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
