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.

650) this.width=650; "Src=" http://images2015.cnblogs.com/blog/17071/201601/17071-20160127165050192-1054839953. JPG "width=" "height=" 241 "style=" border:0px; "/>

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:

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Border:none; "/>

Public enum eitemdatatype {    real (1), Service (2);     Private int value;        private eitemdatatype (int  value)  {        this.value = value;     }     public int getvalue ()  {         return value;    }    public static  eitemdatatype valueof (Int value)  {             switch  (value)  {        case 1:             return EItemDataType.Real;         case 2:             return eitEmdatatype.service;              default :            return null;         }    }             }

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Border:none; "/>

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.

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Border:none; "/>

public enum Eitemdatatype {[Description ("Physical")] real=1, [Description ("service")] service=2}

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Border:none; "/>


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:

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Border:none; "/>

Enumeration values are more readable if (orderInfo.orderStatus.equals (eorderstatus.shipped)) {//do something}//generally do not, 0 readability is not strong if ( orderinfo.orderstatus==0) {//do something}

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Border:none; "/>

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.

650) this.width=650; "Src=" http://images2015.cnblogs.com/blog/17071/201601/17071-20160127165407910-1242841841. PNG "style=" border:0px; "/>

What is the corresponding bytecode after compilation:

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Border:none; "/>

public final class eitemdatatype extends java.lang.enum<eitemdatatype> {   public static final EItemDataType Real;  public static  final eitemdatatype service;  static {};    code:        0: new            #1                   //  class EItemDataType       3: dup        4: ldc            #15                   // String  Real       6: iconst_0       7:  iconst_1       8: invokespecial  #16                   // Method  "<init>":(ljava/lang/string;ii ) v      11: putstatic      #20                   // field real: leitemdatatype;      14: new             #1                    // class EItemDataType      17: dup       18: ldc           # 22                 //  string service      20: iconst_1      21: iconst_2       22: invokespecial  #16                   // Method  "<init>":(ljava/lang/string;ii ) v      25: putstatic      #23                   // field service : leitemdatatype;      28: iconst_2      29:  anewarray      #1                    // class EItemDataType      &NBSP;32:&NBSP;DUP&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;33:&NBSP;ICONST_0&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;34:  getstatic      #20                   // Field Real:LEItemDataType;      37:  Aastore      38: dup      39: iconst_1       40: getstatic      #23                   // field service : leitemdatatype;      43: aastore      44:  putstatic      #25                   // Field ENUM$VALUES:[LEItemDataType;       47: return  public int getvalue ();     code:        0: aload_0       1: getfield        #32                   // field value:i       4: ireturn  public  static eitemdatatype valueof (int);    code:        0: iload_0       1: tableswitch   {  // 1 to 2                      1: 24                      2: 28                default: 32           }      24: getstatic      #20                   // Field  Real:leitemdatatype;      27: areturn      28 : getstatic      #23                   // Field Service:LEItemDataType;       31: areturn      32: aconst_null       33: areturn  public static eitemdatatype[] values ();     Code:       0: getstatic      #25                  //  Field enum$values:[lEitemdatatype;       3: dup       4 : astore_0       5: iconst_0        6: aload_0       7: arraylength        8: dup       9: istore_1       10: anewarray      #1                    // class EItemDataType       13: dup      14: astore_2       15: iconst_0      16: iload_1       17: invokestatic   #42                   // method java/lang/system.arraycopy: (LJAVA/LANG/OBJECT;ILJAVA/LANG/OBJECT;II) V       20: aload_2      21: areturn   public static eitemdatatype valueof (java.lang.String);    code:        0: ldc             #1                    // class EItemDataType       2: aload_0        3: invokestatic   #49                   // method java/lang/enum.valueof: (Ljava/ Lang/class; ljava/lang/string;) ljava/lang/enum;       6: checkcast     &nbSP; #1                    // class eitemdatatype       9: areturn}

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Border:none; "/>

    • 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 Eitemdatatype 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.

650) this.width=650; "Src=" http://images2015.cnblogs.com/blog/17071/201601/17071-20160127164455988-965009830.jpg "Style=" border:0px; "/>

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.

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Border:none; "/>

Public enum Safesingleton implements Serializable {INSTANCE2;    int count;    public void Addcount (int i) {this.count+=i;    } public void PrintCount () {System.out.println (this.count); }}

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Border:none; "/>


The following program will output 5050

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


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.