Experience Summary 53--java Enumeration

Source: Internet
Author: User

Use Java enumerations instead of strings or static variables.

-1. Simple to use

Color Enumeration classes:

public enum Colorenum {

RED, BLACK, GREE, BLUE

}

Call:

public static void Main (string[] args) {

System.out.println (ColorEnum.RED.toString ());

System.out.println (ColorEnum.RED.ordinal ());

}

-2. Custom enumeration values

public enum Colorenum {

RED (1), BLACK (2), GREE (3), BLUE (4);

Private final intvalue;

public int GetValue () {

return value;

}

Colorenum (int value) {

This.value =value;

}

}

System.out.println (ColorEnum.RED.getValue ());

-3. Traverse-Cycle

For (Colorenum item:ColorEnum.values ()) {

System.out.println (Item.getvalue () + ":" + item.tostring ());

}

-4. Type conversion-Converts a string to an enumeration

Stringvalue1= "BLUE";

System.out.println (Colorenum.valueof (value1). ordinal ());

-To convert a number to an enumeration, because it is an array, you need to follow your own starting value

int value2 = 2;

System.out.println (Colorenum.values () [Value2-1].tostring ());

-5. Judging-Switch judgment-First, the number or string is converted to an enumeration to determine

Colorenum value3 = Colorenum.values () [value2-1];

Switch (VALUE3) {

Case RED:

System.out.println (ColorEnum.RED.getValue () + ":" + ColorEnum.RED.toString ());

Break

Case BLACK:

System.out.println (ColorEnum.BLACK.getValue () + ":" + ColorEnum.BLACK.toString ());

Break

Case GREE:

System.out.println (ColorEnum.GREE.getValue () + ":" + ColorEnum.GREE.toString ());

Break

Default

System.out.println (ColorEnum.BLUE.getValue () + ":" + ColorEnum.BLUE.toString ());

}


You can also continue to extend the use of enumerations.


Experience Summary 53--java Enumeration

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.