Java Learning Note 10--Enumeration

Source: Internet
Author: User

Before JDK1.5, Java could have two ways of defining new types: Classes and interfaces. For most object-oriented programming, these two methods seem to be sufficient,

However, in some special cases, these methods are not suitable. For example, to define a color class, it can only have red, Green, blue three values, and any other value

are illegal, then JDK1.5 can construct such code before, but to do a lot of work, but also can bring a variety of unsafe problems. and JDK1.5

The enumeration types (enums) that are introduced later can avoid these problems.

The so-called enumeration is the specified range of values, and all the content can only be obtained from the specified range.

Use simple classes to complete fixed-value problems with colors.

PackageCom.Itmyhome;ClassColor{PublicStaticFinalColorColorred=NewColor(Red);PublicStaticFinalColorColorgreen=NewColor(Blue);PublicStaticFinalColorColorblue=NewColor(Green);PrivateStringName;PublicColor(StringName){This.Name=Name;}PublicStringGetName(){ReturnName;}PublicvoidSetName(StringName){This.Name=Name;} public class t { public static void main (string[] args) throws  Exception{color cred = Colorcolorredsystem.. (cred. Getname} }             /span>                

At this point, the program limits the scope of the objects that can be taken , so the function of enumeration is reached, the above is an enumeration way, in the earliest Java development because there is no enumeration

This concept, so sometimes also using an interface representation.

interface Color{      public static final int RED = 1; public static final int GREEN = 2; public static final int BLUE = 3; }

Defining an enumeration type

After JDK1.5, a new enum of the keyword type is introduced, and the enumeration type can be defined directly, in the following format:

"Public" enum enum type name {Enum Object 1, enum Object 2, ..... Enumeration object N; }

Use the enum keyword definition.

public enum Color {      RED,GREEN,BLUE; }

Because the enumeration already has a range specified, you can use foreach for all of the output, and use the enumeration. VALUES () Form to get all the enumerated content.

PackageCom.Itmyhome;EnumColor{RED,GREEN,BLUE public class t { public static void main (string[] args) throws  Exception{for (color c: color. ()) {system. Out. (c} } }          /span>                

You can also use the content directly on a switch statement.

PackageCom.Itmyhome;EnumColor{RED,GREEN,BLUE;}PublicClassT{PublicStaticvoidMain(String[]Args)ThrowsException{For(ColorC:Color.Values()){Print(C);}}PublicStaticvoidPrint(ColorColor){Switch(Color){CaseRED:{System.Out.println(Red);Break;}CaseGREEN:{System.out. ( "green" break} case blue:{system out. ( "blue" break} default:{system. Out. ( "Unknown color" } } } }        /span>                

Enum

It is clear from the previous that you can define an enumeration using the Enum keyword, which actually represents the Java.lang.Enum type.

That is, an enumeration type declared with an enum is equivalent to defining a class, and this class inherits the Java.lang.Enum class by default.

The Java.lang.Enum class is defined as follows:

public abstract class Enum<E extends Enum<E>> extends Object implements Comparable<E>, Serializable

This class defines the use of generic mechanisms, and implements the comparable interface as well as the serializable interface, proving that this type is comparable and can be serialized.

Main methods for enumerating classes

How to construct an enum class:
protected  Enum(String name, int ordinal)

The construction method receives two parameters, a name that represents the enumeration, and a sequence number that represents the enumeration.

for(Color c:Color.values()){ System.out.println(c.name()+"----"+c.ordinal()); }

If you want to use some text to represent the color information, you can define the attributes and their own construction methods in the enumeration in the form of the earliest color class.

Once you have defined a parameter construct, however, you must explicitly call the constructor method when declaring the enumeration object, and pass the parameters.

PackageCom.Itmyhome;EnumColor{RED(Red),GREEN(Green),BLUE(Blue);Incoming parametersPrivateStringName;PrivateColor(StringName){Defining Construction methodsThis.Name=Name;}PublicStringGetName(){ReturnName;}PublicvoidSetName(StringName){This.Name=Name;}}PublicClassT{PublicStaticvoidMain(String[]Args) throws exception{for  (color c:color. Values ()) {system. Out. (c. Ordinal () + "----" +c. Name () + "----" +c. Getname} } }          /span>                

Java.util.EnumSet and Java.util.EnumMap are two enumeration collections. Enumset guarantees that the elements in the collection are not duplicated; The key in Enummap is the enum type,

and value can be any type

Copyright NOTICE: This article uses the BY-NC-SA agreement to authorize, reproduced the Wheat Field Technical blog article please indicate the source

Original address: Http://itmyhome.com/2015/03/java-study-notes-enum

Java Learning Note 10--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.