Creating an enumeration class

Public enum DbnameEnums {/** scan code/QRCODE, /** Internet */ ORDER}Copy the code

This is the simplest way to write it. But a lot of things are default, so it’s a little hard to understand. We’ll talk about what the default thing is in a second.

Compares whether the values are equal

DbnameEnums a = DbnameEnums.QRCODE; // Assign the DbnameEnums.QRCODE instance object to the variable A DbnameEnums b = dbnameenums.qrcode; // assign the dbnameenums. QRCODE instance object to the variable b if(a.equals(b)){//... }Copy the code

Enumerations are classes. Why can enumerations be compared like this?

QRCODE and ORDER are instance objects of enumeration. But what we are comparing is whether the string values of enumerations are equal. Where are the string values of enumerations? The string values of the enumeration default to QRCODE and ORDER.

The above code, decompiled, looks like this: QRCODE and ORDER are instance objects of the enumeration.

Furthermore, the string value of the enumerated instance object (the toString method value) is QRCODE and ORDER by default.

That’s why you can directly compare the string values of enumerated instances for equality as described above.

Actually, a simpler way to write this is: A == b. Normally, string objects cannot be compared with ==, because you are comparing the address values referenced by string objects, not the string values — so you must use the equal method. So why is enumeration written this way? Because instances of enumerations are unique, the address values referenced by different enumerations must be the same, so you can use == for comparison.

Equals equals equals equals equals equals equals equals equals equals equals equals equals equals equals

Application scenarios

Enumerations are not really suitable for the examples in this article, but are best used when there are only a few values.

reference

www.liaoxuefeng.com/wiki/125259…