Enum Enumeration type, enum Enumeration

Source: Internet
Author: User

Enum Enumeration type, enum Enumeration
Enum Enumeration type

Think in java has to say that it is indeed a classic book, but I can't help but speak out when I see enumeration today. I feel that the content in the book has not explained the usage of enum at all, baidu wrote this blog.

Enum defines an enumeration class as a class. Its definition method is not inheritance. We use the enum keyword to declare the enumeration type. It cannot be declared by explicitly inheriting the abstract class, this class is a final class that cannot be inherited. The enumerated values are static constants of the enumeration class. Note: These enumerated values are all public static final, so you can directly reference this constant through the Enum type name, such as the class name. constant name. Therefore, it is recommended that all enumeration values in the enumeration class be capitalized.

The values in an enumeration object of an enumeration class must be unique. constants of the same type can be grouped into one Enumeration type. One of the outstanding advantages of enumeration is that it can ensure the Singleton, which makes it out of the box with switch. Before jdk1.5, switch can only support int and char Types, limits the use range of the switch. When the switch can be used with enum, this restriction is broken. Theoretically, we can use enum to use switch for any object of the same type.

Think in java this exercise is to create an enum that contains the minimum banknote type and write a switch statement for it. The description of the specific currency is output for each case, this problem is a good explanation of the role of enum. The minimum currency is the double data of 0.1, 0.2, 0.5, and 5. If enum is not used together, switch cannot accept double type as a variable. The usage of enum is described in the Code below.

The first is the definition class of enum.

/* Enumeration can also add methods and attributes like a general class. * You can add static and non-static attributes or methods for it, * All Of This Is as you do in a general class. * The enumeration class is defined through the enum keyword Declaration */public enum Enum_Money {// The enumeration list must be written at the beginning. Otherwise, an error occurs during compilation. The enumeration list only supports the String type, however, brackets can be used to add structures after enumerated values. If it is just the most common enumeration, there is no other way to end the enumeration, you can Not add a plus sign, otherwise you must add Not (0.1), MILD (0.2), MEDIUM (0.5), HOT (1 ), FLAMING (2); private double money;/* values are given through parentheses, and must have a constructor with parameters and an attribute and method, otherwise, a compilation error occurs. * values must be both assigned or not assigned. Some values cannot be assigned. * If values are not assigned, the constructor cannot be written, an error occurred while compiling the assignment. * // The constructor can only be private by default, so that the constructor can only use Enum_Money (double money) {this. money = money;} public double getReturn () {return money ;}}
Then the call class

Public class Test_Enum {public static void main (String [] ARGS) {/* array of enumerated values obtained through values (), in the order declared by enum constants */for (Enum_Money money: enum_Money.values ()/* ordinal () returns the index position of the enumerated values in the enumeration, starting from 0, in the order declared by enum */System. out. println (money. getReturn () + "" + money. ordinal ();/** the enumeration type is a type used to define a variable. to restrict the value assignment of a variable, use the "enumeration name. value "to obtain the value */Enum_Money money = Enum_Money.MEDIUM; switch (money) {case Not: System. out. println ("1 hair"); break; case MEDIUM: System. out. println ("2 hairs"); break; default: break ;}}}

The following is the source code analysis of the enum class.

1. public abstract class Enum <E extends Enum <E>

2. implements Comparable <E>, Serializable {

3.

4. private final String name;

5.

6. // name of the current enumerated constant

7. public final String name (){

8. return name;

9 .}

10.

11. private final int ordinal;

12.

13. // The Order of the current enumerated constants, starting from 0

14. public final int ordinal (){

15. return ordinal;

16 .}

17.

18. // private constructor, which cannot be called. This constructor is used for the code sent by the compiler that responds to the enumeration type declaration.

19. protected Enum (String name, int ordinal ){

20. this. name = name;

21. this. ordinal = ordinal;

22 .}

23.

24. // return the name of the enumerated constant. The default value is the name value. You can override this method to output a more friendly description.

25. public String toString (){

26. return name;

27 .}

28.

29. // compare whether the current enumerated constant is equal to the specified object. Because the enumerated constants are Singleton, The = Operator is called directly. Subclass cannot override this method.

30. public final boolean equals (Object other ){

31. return this = other;

32 .}

33.

34. // return the hash code of the enumerated constant. Same as equals, this method cannot be overwritten.

35. public final int hashCode (){

36. return super. hashCode ();

37 .}

38.

39. // because the enumerated constants are Singleton, cloning is not allowed.

40. protected final Object clone () throws CloneNotSupportedException {

41. throw new CloneNotSupportedException ();

42 .}

43.

44. // compare the enumerated constant with the size of the specified object. They must be of the same type and return the size according to their order in the enumeration Declaration (the first small, the latter large ). Subclass cannot override this method

45. public final int compareTo (E o ){

46. Enum other = (Enum) o;

47. Enum self = this;

48. if (self. getClass ()! = Other. getClass () & // optimization

49. self. getDeclaringClass ()! = Other. getDeclaringClass ())

50. throw new ClassCastException ();

51. return self. ordinal-other. ordinal;

52 .}

53.

54. // obtain the Class Object of the enumeration type to which the enumerated constant belongs.

55. public final Class <E> getDeclaringClass (){

56. Class clazz = getClass ();

57. Class zuper = clazz. getSuperclass ();

58. return (zuper = Enum. class )? Clazz: zuper;

59 .}

60.

61. // return the enumerated constants of the specified enumeration type with the specified name. The name must exactly match the identifier used to declare an enumerated constant in this type. Additional white space characters are not allowed.

62. public static <T extends Enum <T> T valueOf (Class <T> enumType,

63. String name ){

64. T result = enumType. enumConstantDirectory (). get (name );

65. if (result! = Null)

66. return result;

67. if (name = null)

68. throw new NullPointerException ("Name is null ");

69. throw new IllegalArgumentException (

70. "No enum const" + enumType + "." + name );

71 .}

72.

73. // deserialization of enumeration objects is not allowed

74. private void readObject (ObjectInputStream in) throws IOException,

75. ClassNotFoundException {

76. throw new InvalidObjectException ("can't deserialize enum ");

77 .}

78.

79. // deserialization of enumeration objects is not allowed

80. private void readObjectNoData () throws ObjectStreamException {

81. throw new InvalidObjectException ("can't deserialize enum ");

82 .}

83.

84. // The enumeration class cannot have the finalize method, and the subclass cannot override this method.

85. protected final void finalize (){}

86 .}




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.