Reference Blog: http://www.cnblogs.com/zhaoyanjun/p/5659811.html
Directly on the code:
1 ImportJava.util.HashMap;2 ImportJava.util.Map;3 //import Java.lang.Enum; //This TM is the default imported package4 5 Public enumColor {6White (1, "white"),7Red (2, "Red"),8Orange (3, "Orange"),9YELLOW (4, "YELLOW"),TenGreen (5, "green"), OneBlue (6, "blue"), APURPLE (7, "PURPLE"), -Black (8, "BLACK") - ; the - PrivateInteger ID; - PrivateString name; - + PrivateColor (Integer ID, String name) { - This. ID =ID; + This. Name =name; A } at - PublicInteger getId () { - returnID; - } - - PublicString GetName () { in returnname; - } to //up to above is the basic notation for general enumeration classes + - Private StaticMap<integer, color> map =NewHashmap<integer, color>(); the * Static { $ for(Color enums:Color.values ()) {//What's going to come out of this method later?Panax Notoginseng Map.put (Enums.getid (), enums); - } the } + A Public StaticColor ValueOf (intID) {//See the return value clearly the returnValueOf (ID,NULL); + } - $ Public StaticColor ValueOf (intID, color color) { $Color result =map.get (ID); - returnresult = =NULL?Color:result; - } the - //For example, there may be some special quirks in the application that list the names of all colors.Wuyi Public Staticstring[] Listallcolor () { thecolor[] Colors =color.values (); -String[] result =NewString[colors.length]; Wu for(inti = 0; i < colors.length; i++) { -Result[i] =colors[i].getname (); About } $ returnresult; - } - - //Another example, I want to write a nameof . A Public StaticString NameOf (intID) { +Color temp =map.get (ID); the returntemp = =NULL?NULL: Temp.getname (); - } $}
Test it:
1 Public Static voidMain (string[] args) {2 //Hello World3 System.out.println (4 arrays.tostring (Color.values ()));5System.out.println (Color.valueof (3). GetName ());6System.out.println (Color.nameof (3));7 System.out.println (8 arrays.tostring (Color.listallcolor ()));9}
The results are as follows:
All right, let's talk about what values this method returns, and returns the names of those enumeration objects that are not name.
Or, all enumerations under the enumeration class are returned.
In this way, the results of the operation are as follows:
It's clear what the return is.
Java Enumeration Classes