Java enumeration Class (simple to use)

Source: Internet
Author: User

Directly on the code

Usage one (constant):

Package Com.ou.test;import Com.sun.corba.se.impl.util.sunvmcid;public class Enum {public    static void main (string[ ] args) {        Weekday day = weekday.five;        System.out.println (day);//Direct Output FIVE    }}enum weekday{    One,two,three,four,five,six,seven;}

Results:

It looks similar to the static variable used above, and the default ToString method returns the corresponding name.

Usage two (switch):

Package com.ou.test;
public class Enum {
public static void Main (string[] args) {
Color color = Color.green;
switch (color) {
Case RED:
color = Color.green;
Break
Case YELLOW:
color = color.red;
Break
Case GREEN:
color = Color.yellow;
Break
}
SYSTEM.OUT.PRINTLN (color);
}

}
Enum color{
GREEN, YELLOW, RED
}

Results:

 

usage Three: Add a new method to the enumeration
Package com.ou.test;
public class Enum {
public static void Main (string[] args) {
System.out.println (Color.getname (3));
System.out.println (Color.getindex ("green"));
}

}
Enum color{
Red ("Red", 1), Green ("green", 2), BLANK ("White", 3), Yello ("Yellow", 4);
Member variables
private String name;
private int index;
Construction method
Color (String name, int index) {
This.name=name;
This.index=index;
}
Normal method (find value by index number)
public static String getName (int index) {
For (Color c:color.values ()) {
if (c.getindex () = = index) {
return c.name;
}
}
return null;
}
Normal method (find index number by value)
public static int GetIndex (String name) {
For (Color c:color.values ()) {
if (C.getname () ==name) {
return c.index;
}
}
return-1;
}
Get Set
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;
}
}

Results:

 

Java enumeration Class (simple to use)

Related Article

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.