gpt4 book ai didi

java - FindBugs 有争议的描述

转载 作者:行者123 更新时间:2023-11-29 06:47:30 25 4
gpt4 key购买 nike

是我理解错了,还是描述有误?

Equals checks for noncompatible operand (EQ_CHECK_FOR_OPERAND_NOT_COMPATIBLE_WITH_THIS)

This equals method is checking to see if the argument is some incompatible type (i.e., a class that is neither a supertype nor subtype of the class that defines the equals method). For example, the Foo class might have an equals method that looks like:

public boolean equals(Object o) {
if (o instanceof Foo)
return name.equals(((Foo)o).name);
else if (o instanceof String)
return name.equals(o);
else return false;

This is considered bad practice, as it makes it very hard to implement an equals method that is symmetric and transitive. Without those properties, very unexpected behavoirs are possible.

发件人:http://findbugs.sourceforge.net/bugDescriptions.html#EQ_CHECK_FOR_OPERAND_NOT_COMPATIBLE_WITH_THIS

描述说 Foo 类可能有一个类似的 equals 方法,然后说“这被认为是不好的做法”。我没有得到“正确的方法”..

下面的方法应该怎样才对?

@Override
public boolean equals(Object obj) {
if (obj instanceof DefaultTableModel)
return model.equals((DefaultTableModel)obj);
else
return false;
}

最佳答案

当 FindBugs 描述说某某“可能是这种情况”时,他们并不是在说这是一种可接受的做法,而是说这是一种假设情况,会导致出现相关警告。

您不应该说您的对象等于某个 DefaultTableModel,因为没有办法强制该关系的自反性。这意味着给定

DefaultTableModel dtm = new DefaultTableModel(...);
YourObject foo = new YourObject(dtm);
foo.equals(dtm); // true
dtm.equals(foo); // false!

关于java - FindBugs 有争议的描述,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2489649/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com