使用一个对象的实例作为散列表中的关键字,然后用完全新的对象访问它? [英] Using an instance of an object as a key in hashmap, and then access it with exactly new object?

查看:78
本文介绍了使用一个对象的实例作为散列表中的关键字,然后用完全新的对象访问它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有键对象的hasmap,

  HashMap< Key,Object>测试; 

并且创建新的密钥(相同)与密钥..



所以它就像..:

  test.put(new Key(same)) ,someObject); 

(不将该密钥存储在变量中)

所以..过了一会儿......我想要访问hashmap,
,因为我没有这个对象,我试图让新的Key(相同)并使它成为键。
但它不起作用。



如何使它工作? (不保存变量中的第一个对象key)

所以,现在,我使用String对象作为键。

  HashMap< String,Object> 


解决方案

您需要实现 hashCode 等于上。 默认实施这些方法只是检查 instance 是否相等(换句话说,如果它们实际上是同一个对象,那么两个 Object s只会相等。 / p>

进一步阅读



有效的Java - 所有对象通用的方法


I have a hasmap with a key object,

HashMap<Key, Object> test;

and make new Key("the same") as key..

so its like..:

test.put(new Key("the same"), someObject);

(without storing that key in a variable)

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)

So meanwhile, for now, im using String object as a key.

HashMap<String, 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).

Further reading

Effective Java - Methods common to all objects

这篇关于使用一个对象的实例作为散列表中的关键字,然后用完全新的对象访问它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆