A comprehensive interpretation of enumeration types in Java use of enum _java

Source: Internet
Author: User
Tags constant definition lowercase switch case java throws

About enumerations
most places write enumerations for an enumeration and then an example to start a switch, but I want to say that the data from my code is not likely to be an enumeration, usually a string or a number, such as a SQL I parse first to determine the SQL type, by intercepting the SQL token, The interception may be select, DELETE, UPDATE, INSERT, Alter, and so on, but it's all strings, and I'm going to go with the enumeration, I want to convert the string to an enumeration how to do it, and in similar cases, the data from the database are judged by some types, Incoming data from a page, doing different things according to different types, but it's all strings, not enumerations, and the tragedy is that I rarely see anyone write this thing, so I write it down and hope someone can use it.

Why do you use enumerations first? When do we use enumerations better, and what are the advantages of using enumerations?

I think ha, when you are in some category class, and can enumerate, does not change the type, instructs the program to the different place route, uses the enumeration to be the better choice;

It sounds a bit round, but there's an example that might be clear, for example:

We can list the things we do on our daily work day:

Go to work, meet, eat, sleep, etc

We can list the parts of the hospital where the ENT need to check people:

Eyes, nose, ears, mouth, etc

These can be enumerated, and each of the things we have to do in a different way;

Of course you can say:

1, may use the dynamic method assignment, through the configuration file or annotation;

2, can use the constant to achieve similar effect;

3, directly through the string of equals to express, with if else to express

If you use the configuration plus method allocation to do, is flexible, easy to modify, but if we use this in a number of infrequently modified parameters, we tend to add a burden to the configuration, and when you need to look at the system logic, you need to look at the configuration over and over again; however, if the parameters are dynamically transformed information, Using configuration is the right choice;

The use of constants, usually in the switch case is a number, the string in Java can not do switch case, the purpose of using constants than Case 1, Case 2 ... This adds to readability, but string data is also troublesome, unless it is mapped once again, that is not necessary, in fact, the enumeration is almost to help you map, but it will be the code encapsulated just it, since he was done, and grammar support, why not do it! Second, while constants increase readability, he does not have the concept of category and management type, that is, the definition of an enumeration defines a category, which is a good place to enumerate what is needed for that scope, and constants are usually some of their own defined pools, in some public classes or randomly defined, are relatively fragmented, And the enumeration is clearly defined on the switch when the case is within the scope of the lock enumeration, you can control the system and increase readability, and you can view the enumeration information in this category at any time to see what it is like to look at the configuration file, but return to that sentence, if the parameter is variable, Then it is not appropriate to enumerate, enumerations must be enumerable, or the current system consideration scope can be enumerated, such as the hospital ent above, there may be many not listed, but the current hospital only to deal with several parts, do not deal with other, that is the truth; what is mutable, For example, URL parameters to assign to the corresponding method, it is not possible to add a piece of logic to add an enumeration, add a case, at this time with the "Configuration + dynamic Method allocation" better, of course, configuration can be used file or annotation just.

There is the most dirt is, through the string equals, with if else to achieve, oh, this is not bad, but this write more fragmented, second, string matching equals each match each need to compare each character, if your code in a large number of loops, performance is not very good, The rest look more clearly at the above description;

Second, enumerations provide a type-managed component, make the object-oriented system more complete, so that some types of management can be configured and managed, where enumeration can be found in the definition of the enumeration of those who have dealt with, those that have not been dealt with, and these are difficult to do; The operation type of the database defines 10 kinds, then the process of the decision can be used to say the enumeration like the configuration file, but very simple to manage.

Finally, the enumeration is definitely a single case, comparable performance and digital performance, both readable and performance-capable.


Basic use of enum types
with this rationale, we'll look at the enum enum type in Java:
1, you can add variables and methods in the enum

Let's take a look at some code examples:

Public enum State {
    normal ("normal", 1), Update ("updated", 2), Deleted ("deleted", 3), fired ("masked", 4);
    Member variable
    private String name;
    private int index;

    Construct method, note: The constructor method cannot be public because an enum cannot be instantiated
    private state (String name, int index) {
      this.name = name;
      This.index = index;
    }

    Normal method public
    static String getName (int index) {for
      (state c:state. VALUES ()) {
        if (c.getindex () = = Ind Ex) {return
          c.name;
        }
      }
      return null;
    }

    Get Set method public
    String GetName () {return
      name;
    }

    public void SetName (String name) {
      this.name = name;
    }

    public int GetIndex () {return
      index;
    }

    public void Setindex (int index) {
      this.index = index;
    }
  }

From the above code we can see that the enumeration values are defined, followed by a semicolon, and then other variables and methods can be defined. In addition, it is necessary to note that the constructor method in the enum cannot be identified by public, in order to prevent the user from instantiating the enum.

2, can be used to define constants

Let's review how to define constants in Java, and look at the following code:

public static final int normalstate = 1;
private static final int updatestate = 2;

Here we can also use the Enum enumeration to replace the above constant definition, which is as follows:

Public enum State { 
 Normal, Update, Deleted, fired
}

Using enums in Java to define constants has no syntax advantage, but enum enum types can provide more operational functionality.

3, implementation of the interface in the enum

Let's take a look at the following code:

Public interface Icanreadstate {
    void read ();

    String getState ();
}

  Public enum state implements Icanreadstate {
    normal ("normal", 1), Update ("updated", 2), Deleted ("deleted", 3), fired ("masked", 4); 
   private String name;
    private int index;

    Private state (String name, int index) {
      this.name = name;
      This.index = index;
    }

    Interface Method 1

    @Override public
    String getState () {return
      this.name;
    }

    Interface Method 2
    @Override public
    Void Read () {
      System.out.println (This.index + ":" + this.name);
    }
  

As with an interface in a generic class, the Enum enumeration can also inherit the interface and implement all the methods in the interface, the advantage of which is that it is easier to sort, compare, and so on the values in the enumeration, and the encapsulation is better.

Instance
Let's first define a simple enumeration (this is just an example of a simple definition of 3 variables):

public enum Sqltypeenum {
  INSERT, 
  UPDATE,
  DELETE,
  SELECT
}

After parsing the SQL, we get a token, how do we get this token enumeration?

This gets:

String token = "select";
Sqltypeenum sqltypeenum = sqltypeenum.valueof (Token.touppercase ());

If you don't get it, Java throws an exception oh: illegalargumentexception no enum const class SQLTYPEENUM.XXX

The reason I do the capitalization is because the enumeration is also uppercase (of course if your enumeration is lowercase, you are lowercase, but it is troublesome to mix), in fact valueof is called the underlying mapping of the enumeration:

This method is called when the call is called:

So the interior is also a hashmap, hehe!

Once you've got this information, you can do what you want:

Switch (sqltypeenum) {case
 insert: Process insert logic;
 Case Delete: Process delete logic;
 ....
}

OK, sometimes we don't want to use strings such as insert or update directly in the interaction, because there are many times when naming specifications.

For example, define some user action types:

1, Save the user information

2, through the ID to obtain user basic information

3, get the user list

4. Delete user information by ID

Wait a minute

We might define an enumeration to be defined as:

public enum Useroptionenum {
  save_user,
  get_user_by_id,
  get_user_list,
  delete_user_by_id
}

But the method of the system and the configuration of some keywords are usually written as:

Saveuser, Getuserbyid, Getuserbyid, Deleteuserbyid

Of course they have their own rules, but the middle of this layer of mapping, you do not want to do, on the one hand compromise, or the enumeration name all replaced, seemingly very strange, or the method name all replaced, more strange, or do their own mapping, can, a little trouble, in fact, not trouble?

We first write a method that converts the enumerated underline style data to the hump, and puts it in a stringutils:

public static string Convertdbstyletojavastyle (String dbstylestring, Boolean firstupper) {
    dbstylestring = Dbstylestring.tolowercase ();
    String []tokens = Dbstylestring.split ("_");
    StringBuilder StringBuilder = new StringBuilder (128);
    int length = 0;
    for (String token:tokens) {
      if (Stringutils.isnotblank (token)) {
        if (length = 0 &&!firstupper) {
          Stringbuilder.append (token);
        } else {
          char c = token.charat (0);
          if (c >= ' a ' | | c <= ' z ') c = (char) (c-32);
          Stringbuilder.append (c);
          Stringbuilder.append (token.substring (1));
        }
      ++length;
    }
    return stringbuilder.tostring ();
  }

Overload a method:

public static string Convertdbstyletojavalocalstyle (String dbstylestring) {return
    Convertdbstyletojavastyle ( Dbstylestring, false);
  

Then define the enumeration:

public enum Useroptionenum {
  save_user,
  get_user_by_id,
  get_user_list,
  delete_user_by_id;
 
  Private final static map<string, useroptionenum> Enum_map = new hashmap<string, useroptionenum> ();
 
  static {
    for (Useroptionenum v:values ()) {
      enum_map.put (v.tostring (), v); 
    }
  }
 
  Public Staticuseroptionenum fromstring (String v) {
    Useroptionenum useroptionenum = Enum_map.get (v);
    return useroptionenum = null? Default:useroptionenum;
  }
 
  public string toString () {
    string stringvalue = Super.tostring ();
    Return Stringutil.convertdbstyletojavalocalstyle (stringvalue);
  }

OK, so pass an event argument so that if it is: Saveuser, use this:

String event = "Saveuser";//If this gets the parameter
useroptionenum enum = useroptionenum.fromstring (event);

In fact, I made a hashmap, I added a fromstring, because the enumeration has some limitations, some methods do not let you cover, such as the valueof method is the case.

In fact, there is no good to speak of, but to say, and then say enumerate add some custom variables bar, in fact, the enumeration, in addition to being a single case, is similar to the ordinary class, it can also have a construction method, but it is not just by default, you can also provide a custom variable, and then get the set, getting method, but if there is a set, Thread is not safe oh, pay attention to this, so generally the construction method is written:

public enum Sqltypeenum {
  Insert (' INSERT INTO '),
  Delete ("delete from")
  ... omitted;
 
  Private String name;//defines a custom variable
 
  private sqltypeenum (String name) {
   this.name = name;
  }
 
  Public String GetName () {return
    name;
  }
 
  public string toString () {return
    name + "I";//Override toString Method
 }
 //generally does not recommend public
 void SetName (String Name) {
    this.name = name;
 }
}

Under Call:

Sqltypeenum sqltypeenum = sqltypeenum.valueof ("INSERT");
System.out.println (sqltypeenum);
System.out.println (Sqltypeenum.getname ());

Not recommended also called under:

Sqltypeenum.setname ("I am");

On another thread:

Sqltypeenum sqltypeenum = sqltypeenum.valueof ("INSERT");
System.out.println (sqltypeenum);
System.out.println (Sqltypeenum.getname ());

Found the result was changed, hehe!

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.