The enum Enumeration type is newly defined in Versions later than Java SE 5.0. Prior to this version, there was a common method for enumeration classes, which was learned in the video...
class WeekDay{public static final WeekDay SUN = new WeekDay();public static final WeekDay MON = new WeekDay(); public static final WeekDay TUE = new WeekDay(); public static final WeekDay WED = new WeekDay(); public static final WeekDay THU = new WeekDay(); public static final WeekDay FRI = new WeekDay(); public static final WeekDay SAT = new WeekDay(); public String toString(){ if(this==SUN) return "SUN"; else if (this==MON) return "MON"; else if (this==TUE) return "TUE"; else if (this==WED) return "WED"; else if (this==THU) return "THU"; else if (this==FRI) return "FRI"; else return "SAT"; } public static void main(String [] args){ WeekDay weekDay = WeekDay.SUN; System.out.println(weekDay.toString()); }}
The enumeration type is used below. It feels like a class, and some functions can be defined without permission. Of course, it also has functions,
Import Java. util. *; Enum size {small ("S"), medium ("M"), large ("L"), extra_large ("XL"); Private size (string abbreviation) {This. abbreviation = abbreviation;} Public String getabbreviation () {return abbreviation;} private string abbreviation;} public class enums_typesafe {public static void main (string [] ARGs) {rule in = new rule (system. in); system. out. println ("enter a size :( small, medium, large, extra_large)"); string input = in. next (); size = enum. valueof (size. class, input); // you can return the specified name. The enumerated Constant System of the given class. out. println ("abbreviation =" + size. getabbreviation (); If (size = size. extra_large) system. out. println ("Good job -- you paid attention to _. ");}}
The advantage of the new version of Enum type is that it can be determined in the switch statement.
String tostring () returns the enumerated constant name.
Int ordinal () returns the position of the enumerated constant in the enum declaration and starts counting from 0.
Int compareto (E Other) if the enumerated constant appears before other, a negative value is returned; if this = Other, 0 is returned; otherwise, a positive value is returned.
Size [] values = size. values (); The enum class has a values method. You can return an Enum array or enum. values (). length () to obtain the length of the enumerated type variable.