在HashSet/HashMap内部更改对象的hashCode [英] Altering hashCode of object inside of HashSet / HashMap

查看:98
本文介绍了在HashSet/HashMap内部更改对象的hashCode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Java比较陌生,对以下内容感到困惑:在设置ArrayList的内容之前,我通常将对象添加到ArrayList中.即

I am relatively new to Java and am puzzled about the following thing: I usually add objects to an ArrayList before setting its content. I.e.,

List<Bla> list = new ArrayList<>();
Bla bla = new Bla();
list.add(bla);
bla.setContent(); // content influences hashCode

这种方法效果很好.我担心这种方法与HashSetHashMap一起使用时是否会给我带来麻烦.内部哈希表在添加对象时设置.如果在将对象添加到HashSetHashMap(并且其hashCode更改)之后调用setContent()会发生什么?

This approach works great. I am concerned whether this approach will give me trouble when used with HashSets or HashMaps. The internal hash table get set at the time the object is added. What will happen if setContent() gets called after the object was added to HashSet or HashMap (and its hashCode changes)?

我应该在 中添加/放入HashSetHashMap之前完全设置(影响哈希码的)内容吗?通常建议在添加对象之前先完成对象的构建吗?

Should I fully set the (hashCode influencing) content before adding / putting into HashSets or HashMaps? Is it generally recommended to finish building objects before adding them?

非常感谢您的见解.

推荐答案

如果将对象添加到HashSet或HashMap(及其hashCode更改)后调用setContent()会发生什么?

What will happen if setContent() gets called after the object was added to HashSet or HashMap (and its hashCode changes)?

灾难.

在添加/放入HashSets或HashMaps之前,我应该完全设置(影响hashCode的内容)吗?通常建议在添加对象之前完成构建吗?

Should I fully set the (hashCode influencing) content before adding / putting into HashSets or HashMaps? Is it generally recommended to finish building objects before adding them?

是的

相关文档行位于java.util.Set:

注意:如果将可变对象用作集合元素,则必须格外小心. 如果在对象是集合中的元素时更改对象的值以影响等值比较的方式更改集合的行为,则不会指定.这种禁止的特殊情况是不允许集合将自身包含为元素.

Note: Great care must be exercised if mutable objects are used as set elements. The behavior of a set is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is an element in the set. A special case of this prohibition is that it is not permissible for a set to contain itself as an element.

通常来说,这种错误会以元素在集合中处于"和不在"元素中而表现出来,而不同的方法会产生分歧.您可能会很幸运,并且您的元素似乎仍然存在于集合中,或者可能没有出现;这可能是随机发生的.

Generally speaking, this sort of error will manifest itself with elements being both "in" and "not in" your collection, with different methods disagreeing. You may get lucky and your elements may appear to still be in the collection, or they may not; this may happen essentially at random.

这是使大多数对象保持不变的优良作法的众多原因之一-在构造之后一开始就完全不可能进行修改.

This is one of the many, many reasons why it's excellent practice for most of your objects to be immutable -- completely impossible to modify in the first place after construction.

这篇关于在HashSet/HashMap内部更改对象的hashCode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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