1

我有枚举仿真类。main p 和 pp 中的两个对象都在通过==equals测试。两个测试都通过,以防万一

p = PacketType.None; 
pp = PacketType.None; 

并且两者都没有打印以防万一

p = PacketType.StartOfOperation; 
pp = PacketType.None;

equals在方法和运算符中实际调用了什么==?我认为这==不应该通过,因为它必须查看这些对象是否具有相同的指针。换句话说,它应该看起来是同一个对象(在我们的例子中它不是)。

public class PacketType {

    String Name = "9";

    public static final PacketType None = new PacketType("9");
    public static final PacketType StartOfOperation = new PacketType("1");

    PacketType(String Name) {
        this.Name = Name;
    }

    public String toString() {
        return Name;
    }

    public static void main(String[] args) {

        PacketType p = PacketType.None;

        PacketType pp = PacketType.StartOfOperation;

        if (p == pp) {
            System.out.print("==");
        }

        if (p.equals(pp)) {
            System.out.print("equals");
        }
    }
}
4

7 回答 7

1

With objects == should be used to test whether they are references to the same instance of an object. .equals(Object o) should be used to check whether they have an equal value (however this behaviour must be implemented manually in custom objects, else it defaults to == behaviour).

A good example of this is with String people commonly make the mistake of using == over .equals(Object o) when trying to check if strings are equivalent.

String a = "my string";
String b = "my string";
String c = a;
//Each of these should then evaluate to true
a==c
b!=c
a.equals(b)
b.equals(c)

A full explanation of the equals(Object o) method can be found here, I can't find an equivalent for the equality operator == (This one is vague and refers to primitives not Objects).

于 2013-08-13T09:08:45.987 回答
1

你没有override equals,在这种情况下,默认值为equalswill ==

于 2013-08-13T09:12:11.140 回答
0

== 不应该通过,因为它必须查看这些对象是否具有相同的指针。

如果两个引用指向同一个内存对象,则更正 == 将通过。

equals()

如果没有被覆盖,也将通过,因为 equals 的默认实现还使用 . 检查内存对象是否相等==。作为一种好的做法,我们应该为自定义类重写 equals 以实际比较两个对象的属性。如果所有属性都相等,则逻辑上两个对象相等。

于 2013-08-13T09:08:43.987 回答
0

完全可以预期,None != StartOfOperation并且由于您没有覆盖equals,因此您的类从类继承它Object,其实现是

public boolean equals(Object o) { return this == o; }

如您所见,这与刚才的检查完全相同==

于 2013-08-13T09:12:04.817 回答
0

如果您看到 equls 的文档

Object 类的 equals 方法实现了对象上最有区别的可能等价关系;也就是说,对于任何非空引用值 x 和 y,当且仅当 x 和 y 引用同一个对象(x == y 的值为 true)时,此方法才返回 true。

于 2013-08-13T09:13:45.053 回答
0

== 总是用于检查引用是否相等,但 equals() 用于检查引用指向的值。阅读 String 类以深入理解它。(字符串池)

于 2013-08-13T09:13:53.247 回答
0

它们有点不同。

equals()方法存在于java.lang.Object类中,并且期望检查对象状态的等价性。这意味着,对象的内容。而==操作员需要检查实际的对象实例是否相同。

另一个区别是该equals()方法可以被覆盖。这样,您可以将其更改为按您的意愿行事。

于 2013-08-13T09:07:35.653 回答