Enumeration type in Java

Source: Internet
Author: User

The enum keyword is a seemingly small feature. With this keyword, we can create an enumeration type.
In fact, when you use the enum keyword to create a new Enumeration type, you actually create a subclass of the java. lang. Enum class. Each specified value in enumeration can be considered as an instance of this class.
However, we don't need to care about the nature of enumeration. We just need to use it as a way to create a data type, and then we can use the obtained type directly.

Some constants are often used during project development, such as a set of possible values of an attribute. We do not recommend that you directly judge the constant value in the Program (this is prone to errors and requires developers to remember the exact value of each constant ). You can use the enumeration type to save a set of unchanged values.
[Java]
Public enum State {
ACTIVE, CLOSED
}
Enumeration also has a very practical feature, that is, it is applied in the switch statement. This greatly improves the readability of the program.
[Java]
State currentState = State. ACTIVE;
Switch (currentState ){
Case ACTIVE:
// Blabla
Break;
Case CLOSED:
// Blabla
Break;
}
We can add various variables and methods in the enumeration class, or overwrite a method (such as toString ()).
[Java]
Public enum State {
ACTIVE ("Active", 1), CLOSED ("Closed", 0 );
// Member variables, constructor, get/set method, override method, etc.
}
The EnumMap and EnumSet classes allow us to process enumeration types more conveniently.
The EnumMap class is a special implementation of the java. util. Map interface. The key in this interface is an enumeration type.
[Java]
Map <State, Integer> map = new EnumMap <State, Integer> (State. class );
Map. put (State. ACTIVE, 1 );
The EnumSet class implements the java. util. Set interface, which saves a Set of enumerated values. We can use it to save a Set of features/attribute values. EnumSet allows us to operate on a group of enumerations like other Set objects.

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.