在Java中使用任意对象作为Map键的任何缺点? [英] Any disadvantage to using arbitrary objects as Map keys in Java?

查看:357
本文介绍了在Java中使用任意对象作为Map键的任何缺点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中有两种对象,每种对象都有一个对应的另一种对象。

I have two kinds of objects in my application where every object of one kind has exactly one corresponding object of the other kind.

这个关系是一个 Map< type1,type2> ,就像一个HashMap。但不知何故,我怀疑。我可以在地图中使用对象作为键,传递它,让它坐在另一个集合中,并随时从地图检索其合作伙伴?

The obvious choice to keep track of this relationship is a Map<type1, type2>, like a HashMap. But somehow, I'm suspicious. Can I use an object as a key in the Map, pass it around, have it sitting in another collection, too, and retrieve its partner from the Map any time?

一个对象创建后,我传递的是一个标识符,对吧?所以可能没有问题。如果我将序列化和反序列化键,该怎么办?

After an object is created, all I'm passing around is an identifier, right? So probably no problem there. What if I serialize and deserialize the key?

任何其他注意事项?

推荐答案


  1. 关键需要实现 .equals() .hashCode()正确

  2. 不能以任何方式更改为 .hashCode() b $ b
  3. 理想情况下,在 HashMap 中用作键的任何对象都应该是不可变的。

  4. 否则可能会被GCed的对象在用作键和/或值时可能会被保留。

  1. The key needs to implement .equals() and .hashCode() correctly
  2. The key must not be changed in any way that changes it's .hashCode() value while it's used as the key
  3. Ideally any object used as a key in a HashMap should be immutable. This would automatically ensure that 2. is always held true.
  4. Objects that could otherwise be GCed might be kept around when they are used as key and/or value.

这篇关于在Java中使用任意对象作为Map键的任何缺点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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