java泛型类中的equals方法
我有一个名为 ArrayBag 的通用类。我想重写 equals 方法。所以我写了
public boolean equals(T other){
} // gives error
<块引用>错误消息:名称冲突:ArrayBag 类型的方法 equals(T) 与 Object 类型的 equals(Object) 具有相同的擦除功能,但没有 覆盖它
I hava a generic class called ArrayBag. I want to override equals method. So i wrote
public boolean equals(T other){
} // gives error
error message: Name clash: The method equals(T) of type ArrayBag has the same erasure as equals(Object) of type Object but does not
override it
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您尝试重写的 equals 方法需要一个
Object
。当您的代码转换为字节代码时,类型擦除会将您的T
转换为Object
,这与现有的 equals 方法冲突。在该方法内部,您可以处理对
T
的转换。The equals method you are trying to override expects an
Object
. When your code is translated to byte code, type erasure transforms yourT
into anObject
, which conflicts with the existing equals method.Inside the method you can handle casting to
T
.将
equals(T other)
替换为equals(Object other)
,然后在方法内将other
转换为T
执行。Replace
equals(T other)
withequals(Object other)
, and then castother
toT
inside the method implementation.你需要这个。
you need this.
任何时候需要重写方法时,签名都必须与要重写的方法相同。因此,您必须将 Object 作为唯一的参数传递给 equals 方法,以便它能够按需要运行。
作为 Grantham 可靠解决方案的替代方案,您可以使用 getClass() 代替 instanceof,例如,如果您计划扩展泛型类并且不希望子类实例等于您的超类实例。
那看起来像:
Any time you need to override a method, the signature must be the same as the method to be overriden. Therefore you must pass Object as the one and only argument to your equals method for it to function as desired.
As an alternative to Grantham's solid solution, you can use getClass() in place of instanceof, if for example you plan on extending your generic class and don't want sub class instances to ever equal your super class instances.
That would look like: