Differences between Java enumerations and enumerations in. Net

Source: Internet
Author: User

Through a period of project practice, I found that the enumeration in Java is very different from the enumeration in. NET, which initially caused me to enumerate some errors in Java and partially flawed applications, in fact, or because I would habitually think that the Java enumeration in the role and definition and. NET should be similar, after all, both are high-level languages, there are many languages Similarities. This is the old master often said novice good teaching, veteran of the reason, novice brain blank will not have any interference, veterans always with some of their own experience and new knowledge contrast.



Habitual view one: enumerations should be defined in the same way as. NET, as in. NET we can define enumerations like this.

 Public enum Eitemdatatype {    Real=1,    Service=2  }

But Java does not have the ability to write such a graceful enumeration, which may need to be written like this:

 Public enumEitemdatatype {Real (1), Service (2); Private intvalue; PrivateEitemdatatype (intvalue) {         This. Value =value; }      Public intGetValue () {returnvalue; }     Public StaticEitemdatatype ValueOf (intvalue) {            Switch(value) { Case1:            returnEitemdatatype.real;  Case2:            returnEitemdatatype.service; default:            return NULL; }    }            }

finding. NET is much simpler than Java, pay attention to several ways:

    • ValueOf method: The function is to look at the value of an enumeration to get the enumeration, this feature is very common, but in. NET does not need such trouble, you can directly turn the data into an enumeration, such as:
var itemtype= (Eitemdatatype)1;
    • GetValue, it is obvious that you need to convert an enumeration to its corresponding value, and you do not need to call the method to take a value in. NET, or you can make a strong transition, for example:
var itemtypevalue= (int) eitemdatatype.real;
    • Private constructors, we can pass how many parameters, such as the common we need to display this enumeration value corresponding to the Chinese description, in Java We just need to add a name parameter in the constructor, but in. NET because there is no such goods can not do this, but by Atrribute to complete.
 Public enum eitemdatatype {    [Description (" real ")]    Real=1,    [Description (" service ")]    Service=2  }


Habitual view two: because. NET enumeration is a value type, I take it for granted that the enumeration of Java is also a value type. The previous understanding of. NET is that some values are reflected in the program in a more readable way, such as order status, order type, and so on, such as:

// enumeration values are more readable if (OrderInfo.orderStatus.equals (eorderstatus.shipped)) {    //dosomething} // generally not so, 0 readability is not strong if (orderinfo.orderstatus==0) {    //dosomething}

Self-description of enumeration type:

    • The Eitemdatatype.class file is found in the compiled file, which shows that the Java enumeration is actually the same as the normal class, since it is a class, it is certainly not a value type, and the reference type in it contains class type.

What is the corresponding bytecode after compilation:

 Public Final classEitemdatatypeextendsJava.lang.enum<eitemdatatype> {   Public Static FinalEitemdatatype Real;  Public Static FinalEitemdatatype Service; Static {}; Code:0:New#1//class Eitemdatatype3: DUP4:LDC #15//String Real6: Iconst_07: Iconst_18:invokespecial #16//Method "<init>":(ljava/lang/string;ii) V11:putstatic #20//Field Real:leitemdatatype;14:New#1//class Eitemdatatype17: DUP18:LDC #22//String Service20: Iconst_121st: Iconst_222:invokespecial #16//Method "<init>":(ljava/lang/string;ii) V25:putstatic #23//Field Service:leitemdatatype;28: Iconst_229:anewarray #1//class Eitemdatatype32: DUP33: Iconst_034:getstatic #20//Field Real:leitemdatatype;37: Aastore38: DUP39: Iconst_140:getstatic #23//Field Service:leitemdatatype;43: Aastore44:putstatic #25//Field Enum$values:[leitemdatatype;47:return   Public intGetValue (); Code:0: Aload_01:getfield #32//Field value:i4: Ireturn Public StaticEitemdatatype ValueOf (int); Code:0: Iload_01:tableswitch {//1 to 21:24-2:28default: 32          }      24:getstatic #20//Field Real:leitemdatatype;27: Areturn28:getstatic #23//Field Service:leitemdatatype;31: Areturn32: Aconst_null33: Areturn Public Staticeitemdatatype[] VALUES (); Code:0:getstatic #25//Field Enum$values:[leitemdatatype;3: DUP4: Astore_05: Iconst_06: Aload_07: Arraylength8: DUP9: Istore_110:anewarray #1//class Eitemdatatype13: DUP14: astore_215: Iconst_016: Iload_117:invokestatic #42//Method java/lang/system.arraycopy: (LJAVA/LANG/OBJECT;ILJAVA/LANG/OBJECT;II) V20: Aload_221st: Areturn Public Staticeitemdatatype valueOf (java.lang.String); Code:0:LDC #1//class Eitemdatatype2: Aload_03:invokestatic #49//Method java/lang/enum.valueof: (Ljava/lang/class; ljava/lang/string;) Ljava/lang/enum;6:checkcast #1//class Eitemdatatype9: Areturn}
    • is a final type and is not allowed to inherit from another type
    • Inherits the Java.lang.Enum class, which means that the enumeration is a class
 Public Final class extends java.lang.enum<eitemdatatype> {
    • All of the enumeration values are defined as static values and are present in constant form.
 Public Static Final Eitemdatatype Real;
    • Looking at the next special method, because the enumeration inherits the Java.lang.Enum class, it naturally has some practical methods:
 Public Static Eitemdatatype valueOf (java.lang.String);

This is a string parameter type method, and I defined above valueof (int value) very much like, its purpose is to obtain the enumeration value according to certain conditions, but the way is different, the former is the result of the enumeration value ToString to get the enumeration value, corresponding to toString, for example: EItemDataType.Real.toString () it equals "Real", then calls Eitemdatatype.valueof ("Reail"), It is equal to eitemdatatype.real this value. Custom valueof (int value) mode The personal feeling is not very good, because it is easy to conflict with the method that comes with it, it is better to change the name, such as the value of what.

Finally, let's look at the wonderful features that enumerations can achieve: a single case (a diary that was written before. NET: Cliché: one-piece mode). When I first saw that the Java singleton could be implemented by enumeration, I was stunned, and the biggest response was that the enumeration was a stored value. How is it related to singleton? Is the singleton not a class thing? In fact, through the above understanding, enumeration is a class, then think of a single example will not have any doubt, it as a common class is not good, we look at a simple example of the count: according to the structure of the bytecode above, the INSTANCE2 will be defined as a static variable, It is the characteristic of static variable uniqueness that realizes the singleton and is thread-safe.

 Public enum Implements Serializable {    INSTANCE2;     int count;      Public void addcount (int  i)    {        this. count+=i;    }       Public void PrintCount ()    {        System.out.println (this. Count);    }}


The following program will output 5050

        for (int i=1;i<=100;i++) {            SafeSingleton.INSTANCE2.addCount (i);        }        SafeSingleton.INSTANCE2.printCount ();

Enumerations in Java are a special type of data that, in addition to the ability to store value, has a class feature that is larger than. NET, but is more complex to implement.

Differences between Java enumerations and enumerations in. Net

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.