This is my fourth day of the Gwen Challenge
When the company returned a unified result set, the error code and description of the use of enumeration type for unified management, so I have a little understanding of enumeration type, before the development of the time rarely use enumeration type, always feel that enumeration knowledge is a little bit poor.
The scenario pattern shows that we usually need to get the day of the week, but we get the form of array 1-7, so we need to process, the implementation code is as follows.
1. Simple program to achieve enumeration function
Please note the key issue, we need to limit the range of values!
package com.shxt.demo01;
public class Week {
// Define objects for seven weeks
public static final Week SUNDAY = new Week("Sunday");
public static final Week MONDAY = new Week("Monday");
public static final Week TUESDAY = new Week("Tuesday");
public static final Week WEDNESDAY = new Week("Wednesday");
public static final Week THURSDAY = new Week("Thursday");
public static final Week FRIDAY = new Week("Friday");
public static final Week SATURDAY = new Week("Saturday");
private String date;
// Note that the private constructor used here cannot be instantiated externally
private Week(String date){
this.date = date;
}
public String getDate(a) {
return date;
}
public void setDate(String date) {
this.date = date;
}
// Get date array, get data from fixed week
public static Week getInstance(int week){
switch (week){
case 1:
return SUNDAY;
case 2:
return MONDAY;
case 3:
return TUESDAY;
case 4:
return WEDNESDAY;
case 5:
return THURSDAY;
case 6:
return FRIDAY;
case 7:
return SATURDAY;
default:
return null;// Wrong value}}}Copy the code
Test code:
package com.shxt.demo01;
import java.util.Calendar;
public class WeekTest {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
//System.out.println(calendar.get(Calendar.DAY_OF_WEEK));
Week week = Week.getInstance(calendar.get(Calendar.DAY_OF_WEEK));
if(week! =null){ System.out.println(week.getDate()); }}}Copy the code
Code description:
The above program privatized the constructor in class Week, and then prepared several instantiation objects in the class. If you want to get an instance of class Week, you can only use MONDAY… SUNDAY7 objects, which effectively limits the value range of objects
Using the specified scope of the Week object above, we see that each object is numbered by a constant. Each object is identified with a constant, so we can also use an interface to define a range of constants (this approach is less personal).
package com.shxt.demo02;
public interface Week {
// Auto-complete public static final
int SUNDAY = 1;
int MONDAY = 2;
int TUESDAY = 3;
int WEDNESDAY = 4;
int THURSDAY = 5;
int FRIDAY = 6;
int SATURDAY = 7;
}
Copy the code
But enumerations through interfaces are problematic, resulting in incorrect operations
package com.shxt.demo02;
public class WeekTest {
public static void main(String[] args) {
System.out.println(Week.SATURDAY+Week.FRIDAY);// Add the data of the week, there is no such result}}Copy the code
With our approach, users want to know exactly how many weeks are available (assuming you don’t know), so the implementation code is complicated and the sacrifice is high, so similar problems were solved after JDK1.5.
2. Define enumeration types
After JDK1.5, a new keyword type — enum — was introduced. Enumeration types can be defined directly in the following syntax
public enumEnumeration type name{enumeration object1, enumeration object2, enumeration object3. , enumeration object N}Copy the code
Example 1: Define an enumeration type
package com.shxt.demo03;
public enum Week {
SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY;
}
Copy the code
Example 2: Fetching enumeration content
package com.shxt.demo03;
public class Test01 {
public static void main(String[] args) {
Week w = Week.MONDAY;/ / get MONDAYSystem.out.println(w); }}/* The result is: MONDAY */
Copy the code
This result doesn’t feel very useful, we need to step by step, using this method can avoid the problem of using the interface before, right
package com.shxt.demo03;
public class Test02 {
public static void main(String[] args) {
System.out.println(Week.MONDAY+Week.FRIDAY);/ / error}}Copy the code
Enumeration data can also be used in the form “enumeration.values ()”, turning all enumerations into an array of objects, and then directly using foreach.
Example 3: Output enumeration content using foreach
package com.shxt.demo03;
public class Test03 {
public static void main(String[] args) {
Week[] weeks = Week.values();
for(Week w : weeks){ System.out.println(w); }}}Copy the code
Example 4: Determine using the Switch
This is all a brief introduction, and there will be more detailed introductions later
package com.shxt.demo03;
public class Test04 {
public static void main(String[] args) {
Week[] weeks = Week.values();
for(Week w : weeks){ print(w); }}public static void print(Week week){
switch (week){
case SUNDAY:
System.out.println("Sunday");
break;
case MONDAY:
System.out.println("Monday");
break;
case TUESDAY:
System.out.println("Tuesday");
break;
case WEDNESDAY:
System.out.println("Wednesday");
break;
case THURSDAY:
System.out.println("Thursday");
break;
case FRIDAY:
System.out.println("Friday");
break;
case SATURDAY:
System.out.println("Saturday");
break;
default:
System.out.println("What the hell??");
break; }}}Copy the code
The use of enumerations described in the above process is rarely used in actual development, and developers must further understand enumeration types
3. Dig deeper into enumerated types
The enum keyword is used to define an enum type. In fact, this keyword is written on the java.lang. enum class. An enum type declared with enum is equivalent to defining a class, and this class inherits from the java.lang. enum class by default
public abstract class Enum<E extends Enum<E>>
extends Object
implements Comparable<E>, Serializable
Copy the code
Serial number | Method names | type | describe |
---|---|---|---|
1 | protected Enum(String name,int ordinal) | structure | Creates an enumeration object by receiving the enumeration’s name and enumeration constant |
2 | protected final Object clone() throws CloneNotSupportedException |
ordinary | Clone enumeration object |
3 | public final int compareTo(E o) | ordinary | Object to compare |
4 | public final boolean equals(Object other) | ordinary | Compare two enumerated objects |
5 | public final int hashCode() | ordinary | Returns the hash code of the enumerated constant |
6 | public final String name() | ordinary | Returns the name of this enumeration |
7 | public final int ordinal() | ordinary | Returns the ordinal number of an enumerated constant |
8 | public static <T extends Enum> T valueOf(Class enumType, String name) |
ordinary | Returns an enumeration constant of the specified enumeration type with the specified name |
Example 1: Get information about enumerations
package com.shxt.demo03;
public enum Week {
SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY;
}
Copy the code
package com.shxt.demo03;
public class Test05 {
public static void main(String[] args) {
for (Week w : Week.values()) {
System.out.println(w.ordinal()+"- >"+w.name()); }}}0->SUNDAY 1->MONDAY 2->TUESDAY 3->WEDNESDAY 4->THURSDAY 5->FRIDAY 6->SATURDAY */
Copy the code
Example 2: Assign a value to a property via a constructor
Each enumeration class has several objects specified by it. Of course, each enumeration can contain multiple properties. A semicolon must be added at the end of the sequence of enum instances.
package com.shxt.demo04;
public enum Week {
SUNDAY("Sunday".7),MONDAY("Monday".1),TUESDAY("Tuesday".2),
WEDNESDAY("Wednesday".3),THURSDAY("Thursday".4),FRIDAY("Friday".5),SATURDAY("Saturday".6);
private String name;
private int index;
// constructor
private Week(String name,int index){
this.name = name;
this.index = index;
}
public String getName(a) {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getIndex(a) {
return index;
}
public void setIndex(int index) {
this.index = index; }}Copy the code
The Week enumeration class adds two properties, name and index, and sets the contents of the name and index properties through a private constructor that must be invoked because the constructor for two parameters is explicitly defined in Week.
package com.shxt.demo04;
public class Test05 {
public static void main(String[] args) {
for (Week w : Week.values()) {
System.out.println("The serial number."+w.ordinal()+"Enumeration name :"+w.name()+"Attribute name value:+w.getName()+"Attribute index value :"+w.getIndex()); }}}/** The result is: Enumeration name :SUNDAY Attribute name Value :SUNDAY Attribute index value :7 No. :1 Enumeration name :MONDAY Attribute index value :1 No. :2 Enumeration name :TUESDAY attribute name value :TUESDAY attribute index value :2 Number :3 Enumeration name :WEDNESDAY Attribute name Value :WEDNESDAY Attribute index value :3 Number :4 Enumeration name :THURSDAY attribute name value :THURSDAY attribute index value :4 Number :5 Enumeration name :FRIDAY Attribute name value :FRIDAY Attribute index value :5 Serial number :6 Enumeration name :SATURDAY Attribute name Value :SATURDAY Attribute index value :6 */
Copy the code
Example 3: Override the enumeration method toString
package com.shxt.demo05;
public enum Week {
SUNDAY("Sunday".7),MONDAY("Monday".1),TUESDAY("Tuesday".2),
WEDNESDAY("Wednesday".3),THURSDAY("Thursday".4),FRIDAY("Friday".5),SATURDAY("Saturday".6);
private String name;
private int index;
// constructor
private Week(String name, int index){
this.name = name;
this.index = index;
}
@Override
public String toString(a) {
return "Week{" +
"name='" + name + '\' ' +
", index=" + index +
'} '; }}Copy the code
package com.shxt.demo05;
public class Test05 {
public static void main(String[] args) {
for(Week w : Week.values()) { System.out.println(w); }}}/** The result is: Week{name=' Sunday ', index=7} Week{name=' Monday ', index=1} Week{name=' Tuesday ', index=2} Week{name=' Wednesday ', Index =4} Week{name=' Friday ', index=5} Week{name=' Saturday ', index=6} */
Copy the code
Example 4: Using a comparator
The Comparable interface is already implemented in the Enum class, so the content of the enumerated class itself can be sorted. Just to test the results, we described in the class set that TreeSet can be sorted directly. The sorting rules are based on the Comparable interface
package com.shxt.demo06;
public enum Week {
SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY;
}
Copy the code
import java.util.TreeSet;
public class Test01 {
public static void main(String[] args) {
Set<Week> weekSet = new TreeSet<>();
// Save data randomly
weekSet.add(Week.FRIDAY);
weekSet.add(Week.MONDAY);
weekSet.add(Week.THURSDAY);
weekSet.add(Week.WEDNESDAY);
weekSet.add(Week.TUESDAY);
weekSet.add(Week.SATURDAY);
weekSet.add(Week.SUNDAY);
for (Week w:weekSet){
System.out.println(w.ordinal()+"-- >"+w.name()); }}}Copy the code
The order of the iterated data is sorted according to the ordinal attribute.
4. Class set support for enumeration
(1)EnumMap
EnumMap is a subclass of the Map interface. Therefore, EnumMap operates in the form of a Map. Key =>value
package com.shxt.demo07;
public enum Color {
RED,YELLOW,BLUE;
}
Copy the code
package com.shxt.demo07;
import java.util.EnumMap;
import java.util.Map;
public class EnumMapTest {
public static void main(String[] args) {
Map<Color,String> map = new EnumMap<Color, String>(Color.class);
map.put(Color.RED,"Red");
map.put(Color.YELLOW,"Yellow");
map.put(Color.BLUE,"Blue");
System.out.println("********** outputs the entire enumeration and its corresponding value ************");
for(Color c : Color.values()){
System.out.println(c.name()+"Value in map :"+map.get(c));
}
System.out.println("********** get all keys ***************************");
for (Color c : map.keySet()){
System.out.println("KEY="+c.name());
}
System.out.println("********** get all the content ***************************");
for (String s : map.values()){
System.out.println("Value="+s); }}}Copy the code
I am not quite clear about the application scenario of the above code, please leave a message if you have a clear message
###(2)EnumSet
EnumSet is a subclass of the Set interface, so its contents cannot be repeated. Instead of instantiating EnumSet directly with the keyword new, use static methods provided by this class
The serial number | Method names | type | describe |
---|---|---|---|
1 | public static <E extends Enum<E>> EnumSet<E> allOf(Class<E> elementType) |
ordinary | Set the entire contents of the enumeration into EnumSet |
2 | public static <E extends Enum<E>> EnumSet<E> of(E first,E… rest) |
ordinary | Creates an EnumSet object that contains the enumeration specified |
3 | public static <E extends Enum<E>> EnumSet<E> copyOf(Collection<E> c) |
ordinary | Creates an EnumSet object from the specified Collection |
4 | public static <E extends Enum<E>> EnumSet<E> complementOf(EnumSet<E> s) |
ordinary | Creates an enumeration whose element type is the same as the specified enumeration set Set, which initially contains all elements of this type that are not contained in the specified set. |
5 | public static <E extends Enum<E>> EnumSet<E> noneOf(Class<E> e) |
ordinary | Creates an empty collection that can receive the specified type |
Example 1: Set all enumerations into the EnumSet collection
package com.shxt.demo08;
import java.util.EnumSet;
enum Color {
RED,YELLOW,BLUE;
}
public class DenumSetDemo01 {
public static void main(String[] args) {
EnumSet<Color> set = EnumSet.allOf(Color.class);// Set all of the enumeration data into the EnumSet object
for(Color c : set){ System.out.println(c); }}}Copy the code
Example 2: Set an enumeration data to the EnumSet combination
package com.shxt.demo08;
import java.util.EnumSet;
enum Color {
RED,YELLOW,BLUE;
}
public class DenumSetDemo02 {
public static void main(String[] args) {
EnumSet<Color> set = EnumSet.of(Color.YELLOW);// Set an enumeration content
for(Color c : set){ System.out.println(c); }}}Copy the code
Example 3: Only a collection of specified enumerated types can be placed
package com.shxt.demo08;
import java.util.EnumSet;
enum Color {
RED,YELLOW,BLUE;
}
public class DenumSetDemo03 {
public static void main(String[] args) {
EnumSet<Color> set = EnumSet.noneOf(Color.class);// Create an object that can be typed as Color
set.add(Color.YELLOW);
set.add(Color.BLUE);
for(Color c : set){ System.out.println(c); }}}Copy the code
Other methods do not do the test, feel no practical use, here omitted… Forgive me
5. Let enumerations implement an interface
Enumeration classes can also implement an interface, but because all that exists in the interface are the drawn methods, each object in the enumeration class must implement the abstract methods in the interface separately
package com.shxt.demo09;
interface Print{
String getColor(a);
}
enum Color implements Print{
RED{
@Override
public String getColor(a) {
return "Red";
}
},YELLOW{
@Override
public String getColor(a) {
return "Yellow";
}
},BLUE{
@Override
public String getColor(a) {
return "Blue"; }}; }public class InterfaceEnumDemo01 {
public static void main(String[] args) {
for(Color c : Color.values()){ System.out.println(c.getColor()); }}}Copy the code
Or you could write it this way
package com.shxt.demo10;
interface Print{
String getColor(a);
}
enum Color implements Print {
RED("Red"),YELLOW("Yellow"),BLUE("Blue");
private String name;
private Color(String name){
this.name = name;
}
@Override
public String getColor(a) {
return this.name; }}public class InterfaceEnumDemo01 {
public static void main(String[] args) {
for(Color c : Color.values()){ System.out.println(c.getColor()); }}}Copy the code
6. Define abstract methods in enumerated classes
package com.shxt.demo11;
enum Color {
RED("Red") {
@Override
public String getColor(a) {
return "Red = >"+this.name;
}
},YELLOW("Yellow") {
@Override
public String getColor(a) {
return "Huang huang = >"+this.name;
}
},BLUE("Blue") {
@Override
public String getColor(a) {
return "Light light blue = >"+this.name; }};protected String name;
private Color(String name){
this.name = name;
}
public abstract String getColor(a) ;
}
public class AbstractEnumDemo01 {
public static void main(String[] args) {
for(Color c : Color.values()){ System.out.println(c.getColor()); }}}Copy the code