valueOf usage in enumeration

The characteristics of Enum are as follows:
1. It cannot have a public constructor, which ensures that client code cannot create a new instance of enum.  
2. All enumeration values ​​are public, static, final. Note that this is only for enumeration values,
we can define any other type of non-enumeration variables just like we define variables in ordinary classes, and these variables can use any modifiers you want.  

  3. Enum implements the java.lang.Comparable interface by default.  

  4. Enum overrides the toString method, so if we call Color.Blue.toString() it returns the string "Blue" by default.  

   5. Enum provides a valueOf method, which corresponds to the toString method. Calling valueOf("Blue") will return Color.Blue. So we need to pay attention to this when we override the toString method, and we should override the valueOf method accordingly.  

  6. Enum also provides the values ​​method, which allows you to easily traverse all enumeration values.  

  7. Enum also has an oridinal method, which returns the order of the enumeration values ​​in the enumeration type. This order is determined by the order in which the enumeration values ​​are declared. Here Color.Red.ordinal() returns 0.  



public enum Color {
	Red,Green,Blue;
}

	@Test
	public void test1()
	{
		
		System.out.println( Color.values().length);
		System.out.println( Color.Blue.toString());
		System.out.println( Color.valueOf("Blue") == Color.Blue);
	}
	
    The execution result is as follows:
3
Blue
true




Here's a structured enumeration:
public enum ColorConstruct {

	RED(1), GREEN(2), BLANK(3), YELLO(4);
	private int index;
	 
	private ColorConstruct(int index) {
        this.index = index;
    }
}

@Test
	public void test2()
	{
		
		System.out.println( ColorConstruct.values().length);
		System.out.println( ColorConstruct.RED.toString());
		System.out.println( ColorConstruct.valueOf("RED") == ColorConstruct.RED);
	}
The execution result is:
4
RED
true















Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326331575&siteId=291194637