What is an enumeration class
There are only a limited number of objects in a class, which is uncertain
For example: week, season, payment method
Order status: Nonpayment, Paid, Delivered, Return, Checked, Fulfilled
Employment status
Thread status:
BLOCKED the thread state of a thread is BLOCKED waiting for the monitor to lock
Thread state of NEW thread that has not been started
RUNNABLE the thread state of the RUNNABLE thread
TERMINATED the thread state of the TERMINATED thread
TIMED_WAITING the thread state of the waiting thread with the specified waiting time
WAITING the thread state of the WAITING thread
When to use enumeration classes
When you need to define a set of constants, if there is only one object in the enumeration class, it can be used as the implementation of singleton mode
Why use enumeration classes
1) For the sake of type safety, before enumerating classes, they are usually represented by static constants
For the representation of gender,
public static final int MAN = 0;
public static final int WOMAN = 1;
First, these variables can be used for addition and subtraction. Of course, we didn't mean that
Second, the meaning is unclear. When we debug, we wanted to output 'male', and the result is 0
2) More elegant code
Hundreds of static constants may be used in a larger program. If they are all written in one file, it is easy to cause naming confusion and the program is troublesome to read
3) Enumerating classes can facilitate us to define the types we want
Enumeration is easy to remember and use, and is equivalent to an interface. When using, you only need to encapsulate the internal data type and limit the data field. Moreover, different processing methods can be called for different enumeration variables
Custom enumeration class
class Season{ // 1. Declare the attribute of Season object private String seasonName; private String seasonDesc; // 2. Privatization constructor private Season(String seasonName, String seasonDesc){ this.seasonName = seasonName; this.seasonDesc = seasonDesc; } // 3. Provide the object of enumeration class public static final Season SPRING = new Season("spring","in the warm spring , flowers are coming out with a rush"); public static final Season SUMMER = new Season("summer","Summer heat"); public static final Season AUTUMN = new Season("autumn","fresh autumn weather"); public static final Season WINTER = new Season("winter","a world of ice and snow"); public String getSeasonName() { return seasonName; } public String getSeasonDesc() { return seasonDesc; } @Override public String toString() { return "Season{" + "seasonName='" + seasonName + '\'' + ", seasonDesc='" + seasonDesc + '\'' + '}'; } } public class test { public static void main(String[] args) { Season spring = Season.SPRING; System.out.println(spring); } }
enum defines enumeration classes
Season1 inherits Java. Net by default Lang. enum, you cannot inherit other classes, and the default is final
Implementation interface
enum Season1 implements info { // Implementation of interface mode 2 allows the objects of enumeration classes to implement the abstract methods in the interface respectively SPRING("spring", "in the warm spring , flowers are coming out with a rush"){ // ordinal() 0 @Override public void show() { System.out.println("It's spring"); } }, // Equivalent to anonymous inner class SUMMER("summer", "Summer heat"){ // 1 @Override public void show() { System.out.println("It's summer"); } }, AUTUMN("autumn", "fresh autumn weather"){// 2 @Override public void show() { System.out.println("It's autumn"); } }, WINTER("winter", "a world of ice and snow"){// 3 @Override public void show() { System.out.println("It's winter"); } }, WUCAN { // 4 @Override public void show() { System.out.println("No reference"); } }; private String seasonName; private String seasonDesc; private Season1() { } private Season1(String seasonName, String seasonDesc) { this.seasonName = seasonName; this.seasonDesc = seasonDesc; } public String getSeasonName() { return seasonName; } public String getSeasonDesc() { return seasonDesc; } // Implementation interface mode I /* @Override public void show() { System.out.println("Same behavior "); }*/ } interface info { void show(); } public class test2 { public static void main(String[] args) { Season1 autumn = Season1.AUTUMN; System.out.println(autumn);// toString() System.out.println(Season1.class.getSuperclass()); Season1[] values = Season1.values(); for (int i = 0; i < values.length; i++) { System.out.println(values[i]); values[i].show(); } Season1 winter = Season1.valueOf("WINTER"); System.out.println(winter);// WINTER Thread.State[] values1 = Thread.State.values(); for (int i = 0; i < values1.length; i++) { System.out.println(values1[i]); } } }
No interface implemented
// If the enumeration class does not implement the interface, the result is the same as that of the custom enumeration class enum Season1 { SPRING("spring", "in the warm spring , flowers are coming out with a rush"),// Equivalent to public static final Season SPRING = new Season("spring", "spring flowers bloom"); SUMMER("summer", "Summer heat"), AUTUMN("autumn", "fresh autumn weather"), WINTER("winter", "a world of ice and snow"), WUCAN ; private String seasonName; private String seasonDesc; private Season1() { } private Season1(String seasonName, String seasonDesc) { this.seasonName = seasonName; this.seasonDesc = seasonDesc; } public String getSeasonName() { return seasonName; } public String getSeasonDesc() { return seasonDesc; } } public class test2 { public static void main(String[] args) { Season1 autumn = Season1.AUTUMN; System.out.println(autumn.name()); System.out.println(autumn); // Output the order of enumerating objects, starting from 0 System.out.println(autumn.ordinal());// 2 Season1 s = Season1.SPRING; System.out.println(s.compareTo(autumn));// -2 System.out.println(s.getDeclaringClass());// class test.Season1 System.out.println(s.getClass());// class test.Season1 System.out.println(autumn.getClass());// class test.Season1 } }
Main methods of Enum class
toString() returns the name of the enumeration object constant
/** * Rewrite the toString method with switch to improve the robustness of the code * @return */ @Override public String toString() { //switch supports Enum type switch (this) { case MONDAY: return "Today is Monday"; case TUESDAY: case WEDNESDAY: return "Today is Wednesday"; case THURSDAY: return "Today is Thursday"; case FRIDAY: return "Today is Friday"; case SATURDAY: return "Today is Saturday"; case SUNDAY: return "Today is Sunday"; default: return "Unknow Day"; } }
values() returns an array of objects of enumeration type / / javap Season1 Class can see
valueOf(String str) can convert a string into a corresponding enumeration class object
Name enumeration constant name. toString is preferred
ordinal gets the order of the current enumeration constants
compareTo return self.ordinal() - other.ordinal()
Getdeclarangclass gets the Class object of the enumeration type to which the enumeration constant belongs. It is used to judge whether the two enumeration constants belong to the same enumeration type
// Enumeration of the above implementation interfaces public class test2 { public static void main(String[] args) { Season1 autumn = Season1.AUTUMN; System.out.println(autumn.name()); System.out.println(autumn); // Output the order of enumerating objects, starting from 0 System.out.println(autumn.ordinal());// 2 Season1 s = Season1.SPRING; System.out.println(s.compareTo(autumn));// -2 System.out.println(s.getDeclaringClass());// class test.Season1 System.out.println(s.getClass());// class test.Season1$1 System.out.println(autumn.getClass());// class test.Season1$3 } }
Clone enumeration type cannot be clone. In order to prevent subclasses from implementing cloning methods, Enum implements the invariant Clone() that only throws CloneNotSupportedException exceptions
switch uses enumeration types
switch uses enumeration type objects and case uses enumeration constants
public static void main(String[] args) { InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); try { System.out.println("Please enter 1-7"); int i = Integer.parseInt(br.readLine()); switch (i) { case 1 : System.out.println(Week.MONDAY); printWeek(Week.MONDAY); break; case 2 : System.out.println(Week.TUESDAY); printWeek(Week.TUESDAY); break; case 3 : System.out.println(Week.WEDNESDAY); printWeek(Week.WEDNESDAY); break; case 4 : System.out.println(Week.THURSDAY); printWeek(Week.THURSDAY); break; case 5 : System.out.println(Week.FRIDAY); printWeek(Week.FRIDAY); break; case 6 : System.out.println(Week.SATURDAY); printWeek(Week.SATURDAY); break; case 7 : System.out.println(Week.SUNDAY); printWeek(Week.SUNDAY); break; } } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } } public static void printWeek(Week week) { switch (week) { case MONDAY : System.out.println(Week.MONDAY.getWeekName()); break; case TUESDAY: System.out.println(Week.TUESDAY.getWeekName()); break; case WEDNESDAY: System.out.println(Week.WEDNESDAY.getWeekName()); break; case THURSDAY: System.out.println(Week.THURSDAY.getWeekName()); break; case FRIDAY: System.out.println(Week.FRIDAY.getWeekName()); break; case SATURDAY: System.out.println(Week.SATURDAY.getWeekName()); break; case SUNDAY: System.out.println(Week.SUNDAY.getWeekName()); break; } } enum Week { MONDAY("Monday"), TUESDAY("Tuesday"), WEDNESDAY("Wednesday"), THURSDAY("Thursday"), FRIDAY("Friday"), SATURDAY("Saturday"), SUNDAY("Sunday"); private final String weekName; Week(String weekName) { this.weekName = weekName; } public String getWeekName() { return weekName; } }
Use = = to compare enumeration types
equals(), which can be compared directly with = = in enumeration types. Equals in Enum is also directly implemented with = =. Its existence is used in Set List Map, and equals is immutable
The = = operator is used to compare States, and NullPointerException will not be raised if both values are null. Conversely, if the equals method is used, a NullPointerException will be thrown:
Pizza.PizzaStatus pizza = null; System.out.println(pizza.equals(Pizza.PizzaStatus.DELIVERED));//Null pointer exception System.out.println(pizza == Pizza.PizzaStatus.DELIVERED);//normal operation
Week status = Week.MONDAY; Week status2 = Week.TUESDAY; Week status3 = Week.MONDAY; System.out.println(status==status3);// true System.out.println(status.equals(status3));// true System.out.println(status==status2);// false System.out.println(status.equals(status2));// false
Continuously updated...