本文介绍了在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?

非常感谢您的见解.

推荐答案

灾难.

是的

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

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

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 14:17