除了不可变的值对象,我什么时候应该覆盖equals()? [英] Apart from immutable value objects, when should I override `equals()`?

查看:46
本文介绍了除了不可变的值对象,我什么时候应该覆盖equals()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很明显,当您处理不可变的值对象时, equals()(当然还有 hashCode())非常有用-映射键,强类型字段您需要在包含它们的对象之间进行比较的值,等等.

It's clear that equals() (and of course hashCode()) are valuable when you're dealing with immutable value objects -- map keys, strongly typed field values that you need to compare across the objects that contain them, etc.

但是除了值对象之外,您真的有多大可能会拥有两个独立构造的实例,并希望它们成为 equal 相等?

But apart from value objects, how often is it really likely that you'll have two independently constructed instances and want them to be equal?

对于我来说,很难想象一个现实的场景,在这种情况下,引用相等实际上不会为您提供所需的东西.在那些特定情况下,似乎场景特定的等效方法( isEquivalentTo(Foo)而不是 equals(Object))会更安全.尤其是对于易变的物体?

It's hard for me to imagine a realistic scenario where referential equality wouldn't, de facto, get you what you want; and in those specific cases, it seems like a scenario-specific equivalence method (isEquivalentTo(Foo) rather than equals(Object)) would be safer. Particularly for mutable objects?

在非值类型中 equals()的用例是什么?

What's the use case for equals() in non-value types?

推荐答案

Um. Set< E> 是可变的,并且具有(有用的) equals()定义.似乎没有用...

Um. Set<E> is mutable, and has a (useful) definition of equals(). That doesn't seem useless...

这篇关于除了不可变的值对象,我什么时候应该覆盖equals()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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