编程技术网

关注微信公众号,定时推送前沿、专业、深度的编程技术资料。

 找回密码
 立即注册

QQ登录

只需一步,快速开始

极客时间

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

lvs071103 面向对象 2022-5-11 10:27 6人围观

腾讯云服务器
除了不可变的值对象,我什么时候应该覆盖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()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程技术网(www.editcode.net)!

腾讯云服务器 阿里云服务器
关注微信
^