开发者

Why is myEnum.ONE not equal to myEnum.ONE.toString()?

开发者 https://www.devze.com 2023-01-13 17:56 出处:网络
I\'ve got the following enum: public enum myEnum { ONE(\"ONE\"), TWO(\"TWO\"); private String name; private myEnum(String 开发者_JAVA技巧name) {

I've got the following enum:

public enum myEnum {
    ONE("ONE"), TWO("TWO");

    private String name;

    private myEnum(String 开发者_JAVA技巧name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return name;
    }
};

My question is why does the following evaluate to false? I suspect it has something to do with the implementation of the equals() method.

(myEnum.ONE).equals(myEnum.ONE.toString())


Generally, objects of different types are not defined equal, because to satisfy the symmetry mandated by the contract of equals, both classes would have to know about each other.

Moreover, because equals must be transitive (which is also mandated by the contract of equals), introducing your rule would have strange consequences. Consider:

enum Color {
    green, red, blue;
}

enum Experience {
    green, novice, veteran;
}

Should Color.green equal Experience.green? Probably not, since experience and color are really different things. But if "green".equals(Color.green) and "green".equals(Experience.green), Color.green must be equal to Experience.green.

So the general rule is: Objects of unrelated types are not equal.


Yes, it's the equals() method. For Enum it looks like this:

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

Now your result is clear: an enum is not the same object as the result of the toString() method.


In your expression the value on the left is an enum. The value on the right is a string.

The longer answer is that .equals in java evaluates by default to mean "the same instance of the same object" unless you explicitly override it with a different form of evaluation. In the case of emums, they are essentially syntactic sugar around a guarantee of single instance values for each element in the enum. The enum equals therefore looks to see if it's the same element.

So, MyENum.ONE is a reference to an instance of MyEmum, of which there is only one. Anytime you have a MyEnum.ONE it's the same instance. if you ask it if something else is equal to it, it will only respond true to a MyEnum.ONE instance.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号