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 中的键,然后使用全


基础教程推荐
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- Struts2 URL 无法访问 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01