Java – the best way to compare enumerations

See the English answer > comparing Java enum members: = = or equals()? 16

Color c1 = Brown,c2 = Red

What is the best way to compare constant values:

if (c1 == Color.Brown) { 
    //is brown
}

or

if (c1.equals(Color.Brown)) {
    //is brown
}

Solution

Use = = It cannot have multiple instances of the same enumeration constant (in the context of the classloader, but let's ignore this), so it is always safe

That is, using equals () is also safe, and reference equality is also performed This is almost a style choice

Personally, I rarely find myself enumerating with if statements I like the switch block

switch (c1) {
    case Brown:
        //is brown
        break;
    case Red:
        //...
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>