/**//* We can loop over the values we put into the enum using the values() method. Note that the enum Seasons is compiled into a separate unit, called EnumDemo$Seasons.class */ publicclass EnumDemo ...{ /**//*declare the enum and add values to it. note that, like in C#, we don't use a ; to end this statement and we use commas to separate the values */ privateenum Seasons ...{ winter, spring, summer, fall } //list the values publicstaticvoid main(String[] args) ...{ for (Seasons s : Seasons.values())...{ System.out.println(s); } } }
榪愯涓婅堪浠g爜浣犲洖寰楀埌 浠ヤ笅緇撴灉:
winter
spring
summer
fall
Enum鐨勫睘鎬ц皟鐢?
涓嬮潰鐨勪唬鐮佸睍紺轟簡璋冪敤enum瀵硅薄鐨勬柟娉?榪欎篃鏄畠閫氬父鐨勭敤娉?
package net.javagarage.enums; /**//* File: EnumSwitch.java Purpose: show how to switch against the values in an enum. */ publicclass EnumSwitch ...{ privateenum Color ...{ red, blue, green } //list the values publicstaticvoid main(String[] args) ...{ //refer to the qualified value doIt(Color.red); } /**//*note that you switch against the UNQUALIFIED name. that is, "case Color.red:" is a compiler error */ privatestaticvoid doIt(Color c)...{ switch (c) ...{ case red: System.out.println("value is "+ Color.red); break; case green: System.out.println("value is "+ Color.green); break; case blue: System.out.println("value is : "+ Color.blue); break; default : System.out.println("default"); } } }