Squire: J2SE5 enumeration example

xiaoxiao2021-03-06  41

One,

Definition enumeration

Public enum grade {

A, B, C, D, F, INCOMPLETE

}

Second, traverse enumeration value

Public void ListGradeValues ​​(PrintStream out) throws oException {

FOR (Grade G: grade.values ​​()) {

Out.println ("Allowed Value: '" G "'");

}

}

Third, using ENUM in Switch

Public void testswitchstatement (PrintStream out) throws oException {

Stringbuffer outputtext = new stringbuffer (student1.getfullname);

Switch (student1.getgrade ()) {

Case A:

OutputText.Append ("Excelled with a grade of a");

Break;

Case B: // Fall Through TO C

Case C:

OutputText.Append ("Passed with a grade of")

.append (student1.getgrade (). TOSTRING ());

Break;

Case D: // Fall Through To F

Case F:

OutputText.Append ("Failed with a grade of")

.append (student1.getgrade (). TOSTRING ());

Break;

Case INCOMPLETE:

OutputText.Append ("DID NOT COMPLETE THE CLASS.");

Break;

DEFAULT: OUTPUTTEXT.APpend ("HAS a grade of") .append (student1.getgrade (). Tostring ()); Break;

}

Out.println (outputText.toString ());

}

Fourth, joint use enumeration and collection

Public enum antstatus {

INITIALIZING,

Compiling,

Copying,

Jarring,

Zipping,

DONE,

Error

}

Public void Testenummap (PrintStream out) throws oException {

// Create a map with the key and a string message

Enummap AntMessages =

New enummap (ANTSTATUS.CLASS);

// Initialize the Map

AntMessages.Put (Antstatus.Initializing, "Initializing Ant ...");

AntMessages.Put (AntStatus.comPiling, "Compiling Java Classes ...");

AntMessages.Put (Antstatus.copy, "Copying Files ...");

AntMessages.Put (Antstatus.jarring, "Jarring Up Files ...");

AntMessages.Put (AntStatus.zipping, "Zipping Up Files ..."); AntMessages.Put (AntStatus.done, "Build Complete.");

AntMessages.Put (AntStatus.Error, "Error Occurred.");

// Iterate and Print Messages

For (AntStatus Status: antstatus.values ​​()) {

Out.println ("For Status" Status ", Message IS:"

AntMessages.get (status);

}

}

Tiger takes the enumeration as a class, which can be from

Antstatus

Class objects have been proved that this object is not only available, but is actually used. In the final analysis, Tiger still regards enumeration as a special class type.

转载请注明原文地址:https://www.9cbs.com/read-78397.html

New Post(0)