Java集中对象的可变字段 [英] mutable fields for objects in a Java Set

查看:194
本文介绍了Java集中对象的可变字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以更正假设,如果你有一个对象包含在一个Java集合<>(或作为一个关键在Map<>)中,用于确定身份或关系的任何字段 hashCode() equals() compareTo()等等)不能改变而不导致集合上的操作的未指定的行为? (编辑:如此其他问题中所暗示的)

Am I correct in assuming that if you have an object that is contained inside a Java Set<> (or as a key in a Map<> for that matter), any fields that are used to determine identity or relation (via hashCode(), equals(), compareTo() etc.) cannot be changed without causing unspecified behavior for operations on the collection? (edit: as alluded to in this other question)

(换句话说,这些字段应该是不可变的,或者你需要从集合中删除对象,然后改变,然后重新插入。)

(In other words, these fields should either be immutable, or you should require the object to be removed from the collection, then changed, then reinserted.)

我要求的原因是我正在阅读 Hibernate注释参考指南,它有一个例子,其中有一个 HashSet<玩具> 但是玩具类具有可变的并且也在 hashCode()中使用的字段 name serial 计算...一个红色的标志在我脑海中消失了,我只是想确保我理解它的含义。

The reason I ask is that I was reading the Hibernate Annotations reference guide and it has an example where there is a HashSet<Toy> but the Toy class has fields name and serial that are mutable and are also used in the hashCode() calculation... a red flag went off in my head and I just wanted to make sure I understood the implications of it.

推荐答案

的javadoc表示

The javadoc for Set says


注意:如果
可变对象用作设置
元素,则必须非常小心。如果对象的值是
以影响
的方式更改,则集合的行为不是
,而对象是
则是集合中的元素。这个禁止的一个特殊情况是
允许一个包含
本身作为一个元素。

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.

这只是意味着你可以在一个集合中使用可变对象,甚至改变它们。您只需确保更改不会影响设置查找项目的方式。对于 HashSet ,这将不需要更改用于计算 hashCode()的字段。

This simply means you can use mutable objects in a set, and even change them. You just should make sure the change doesn't impact the way the Set finds the items. For HashSet, that would require not changing the fields used for calculating hashCode().

这篇关于Java集中对象的可变字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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