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

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

问题描述

我对 Java 比较陌生,对以下事情感到困惑:我通常在设置内容之前将对象添加到 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

这种方法效果很好.我担心这种方法在与 HashSets 或 HashMaps 一起使用时是否会给我带来麻烦.内部哈希表在添加对象时设置.如果在将对象添加到 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)?

在添加/放入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?

非常感谢您的见解.

推荐答案

如果在将对象添加到 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 上:

The relevant line of documentation is on 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天全站免登陆