Re-walk Java--step 3

Source: Internet
Author: User

Java Foundation (III) enumeration usage
Usage One: Constants

public enum Color {
Red,green,red,yellow;
}
Usage Two: custom methods in enumerations
/**
* Custom Methods in enumerations
*/
public enum Color {
Red ("Red", 1), Green ("green", 2), BLANK ("White", 3), YELLOW ("Yellow", 4);
Member variables
public String name;
public int index;

constructor function
Private Color (String name, int index) {
THIS.name = name;
This.index = index;
}

Common methods
public static String getName (int index) {
For (Color c:color.values ()) {
if (c.getindex () = = index) {
return c.name;
}

}
return null;
}

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;
}
}
Usage Three: Switch
public class TrafficLight {
Color signal = color.red;

public void Change () {
Switch (signal) {
Case RED:
signal = Color.green;
Break
Case GREEN:
signal = Color.yellow;
Break
Case YELLOW:
signal = color.red;
Break
}
}
}
Usage Four: Enumerate implementation interfaces
Enumeration inherits the Java.lang.Enum.java does not support multiple inheritance, but enumerations can implement interfaces.

Usage Five: Enumerate collections
The enumeration collection has Enummap and Enumset two, the key value in the Enummap collection is an enumeration, value can be any type, and numset guarantees that the elements in the collection are not duplicated.
Instance usage:
public static void Testenummap () {
Enummap<light, string> currlight = new Enummap<light, string> (Light.class);
Currlight.put (Light.green, "green light");
Currlight.put (light.red, "red light");
Currlight.put (Light.yellow, "yellow Light");
For (Light aLight:Light.values ()) {

System.out.println ("[key=" + alight.name () + ", value="

+ currlight.get (alight) + "]");

}
}

Re-walk Java--step 3

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.