Use of enumerations in Java

Source: Internet
Author: User
Tags constant definition

Constants and enumerations

One, the constant definition method

A constant is a fixed amount of values, generally can be divided into literal constants and named constants, such as the number 1,2,1.3, the string "abc", these are literal constants, and named constants are we use some meaningful names to represent literal constant values, often named constants help us to better understand the logic of the program.

In Java, we usually use public static final ... method to define constants, such as: public static final int max_value = 1000;

Before JDK1.5, if we need to represent a set of related constants, we can do it in the following way:

01./**

02. * Week

* @author

04. *

05. */

06.public class WeekDay {

. public static Final int MONDAY = 1; Monday

public static final int Tuesday = 2; Tuesday

Wednesday public static final int = 3; Wednesday

public static final int Thursday = 4; Thursday

public static final int FRIDAY = 5; Friday

public static final int SATURDAY = 6; Saturday

public static final int SUNDAY = 0; Sunday

14.}

Now, we can encapsulate the relevant constants into an enumeration type, and the enumeration provides more methods than constants.

Second, enumeration definition method

The simple way to define enumerations is as follows:

01./**

02. * Week Enumeration

* @author

04. *

05. */

06.public enum WeekDay {

MONDAY, Tuesday, Wednesday, Thursday, FRIDAY, SATURDAY, SUNDAY

08.}

Can we give a numeric value to each enumeration type as if it were constant, the answer is yes.

By default, each enumeration value corresponds to an integer numeric value. The first enumeration value corresponds to the number 0, the second enumeration value corresponds to the number 1, and the subsequent number for each enumeration value is the result of (the previous enumerated value + 1). Of course, we can also specify a value for each enumeration value ourselves.

How do you customize the numeric value corresponding to each enumeration value? Enumeration types provide a constructor method that we can implement by constructing a method with the ToString () method. The modified code is as follows:

01./**

02. * Week Enumeration

03. *

* @author

05. *

06. */

07.public enum WeekDay {

08.//Using the construction method to transmit the parameter

MONDAY (1), Tuesday (2), Wednesday (3), Thursday (4), FRIDAY (5), SATURDAY (6), SUNDAY (0);

10.

One. private int val;

12.

Private WeekDay (int val) {

This.val = val;

15.}

16.

@Override

Public String toString () {

. return string.valueof (This.val);

20.}

21.}

In this view, we can also define member variables and construct methods in enumerations.

It is important to note, however, that the enumeration class is constructed in a very different way from the normal class: The enumeration construction method is called only when constructing an enumeration value? Enumeration construction methods can only be private, not public

A member method can also be defined in the enumeration, and the modified code is as follows:

01./**

02. * Week Enumeration

03. *

* @author

05. *

06. */

07.public enum WeekDay {

08.//Using the construction method to transmit the parameter

MONDAY ("Monday", 1, 1), Tuesday ("Tuesday", 2, 2), Wednesday ("Wednesday", 3, 3), Thursday (

10. "Thursday", 4, 4), FRIDAY ("Friday", 5, 5), SATURDAY ("Saturday", 6, 6), SUNDAY (

11. "Sunday", 0, 7);

12.

private String name; Chinese name

. private int Val; corresponding numeric value

. private int index; Index

16.

WeekDay Private (String name, int val, int index) {

THIS.name = name;

This.val = val;

This.index = index;

21.}

22.

23./**

24. * Get Chinese name

25. *

* @return Chinese name string

27. */

. Public String GetName () {

. return this.name;

30.}

31.

32./**

33. * Get the corresponding value of the enumeration value

34. *

* @return Enumeration corresponding values

36. */

PNS. public int getval () {

. return this.val;

39.}

40.

41./**

42. * Get enumeration value Index

43. *

* @return Index

45. */

. public int GetIndex () {

. return this.index;

48.}

49.

50./**

51. * Set Chinese name

52. *

* @param name

54. * Chinese Name

55. */

. public void SetName (String name) {

THIS.name = name;

58.}

59.

60./**

61. * Set the numeric value

62. *

. * @param val

64. * Value

65. */

Setval public void (int val) {

This.val = val;

68.}

69.

70./**

71. * Set Index

72. *

* @param index

74. * Index

75. */

Setindex public void (int index) {

This.index = index;

78.}

79.

80./**

81. * Get enumeration value by index Chinese name

82. *

* @param index

84. * Index

* @return The Index enumeration value Chinese name

86. */

The. public static String getName (int index) {

WeekDay weekDay:WeekDay.values ()) {

if (weekday.getindex () = = index)

*. return weekday.getname ();

91.}

92.

The. return null;

94.}

95.

@Override.

The. Public String toString () {

98. Return "WeekDay" + super.tostring () + "[name=" + THIS.name + "val="

+ This.val + "index=" + This.index + "]";

100.}

101.}

Notes on using enum types

All enumerations inherit the methods of the enum, which are described in detail below:

1.ordinal (): Returns the order of the enumeration values in the enumeration, which is incremented in order from 0, as defined by the enumeration values.

2.name (): Returns the name of the enumeration value

3.compartTo (E): Because enum implements the comparable interface, you can compare the order of this object with the specified object

4.values (): Returns an array containing all the enumeration values

5.toString (): Returns the name of the enumeration value

6.valueOf (String)/valueof (Class, String): Returns an enumeration value of the specified enumeration type with the specified name

7.equals (object): Compare references to two enumerated objects

We can consider an enumeration as a class and a final class that cannot be inherited, whose enumeration value is the static constant of the class, and we can get an instance of the enumeration by using the following syntax, such as WeekDay WD = Weekday.monday;

A complete example:

01.public class Weekdaytest {

02.

03./**

04. * Defining Enumeration types

05. */

. public enum WeekDay {

07.//Using the construction method to transmit the parameter

MONDAY ("Monday", 1, 1), Tuesday ("Tuesday", 2, 2), Wednesday ("Wednesday", 3, 3), Thursday (

09. "Thursday", 4, 4), FRIDAY ("Friday", 5, 5), SATURDAY ("Saturday", 6, 6), SUNDAY (

10. "Sunday", 0, 7);

11.

private String name; Chinese name

private int val; corresponding numeric value

. private int index; Index

15.

Private WeekDay (String name, int val, int index) {

THIS.name = name;

This.val = val;

This.index = index;

20.}

21st.

22./**

23. * Get Chinese name

24. *

* @return Chinese name string

26. */

. Public String GetName () {

. return this.name;

29.}

30.

31./**

32. * Get the corresponding value of the enumeration value

33. *

* @return Enumeration corresponding values

35. */

Getval public int () {

Panax Notoginseng return this.val;

38.}

39.

40./**

41. * Get enumeration value Index

42. *

* @return Index

44. */

The. public int GetIndex () {

This.index return;

47.}

48.

49./**

50. * Set Chinese name

51. *

* @param name

53. * Chinese Name

54. */

SetName public void (String name) {

THIS.name = name;

57.}

58.

59./**

60. * Set the numeric value

61. *

* @param val

63. * Value

64. */

. public void Setval (int val) {

This.val = val;

67.}

68.

69./**

70. * Set Index

71. *

* @param index

73. * Index

74. */

. public void Setindex (int index) {

This.index = index;

77.}

78.

79./**

80. * Get enumeration value by index Chinese name

81. *

* @param index

83. * Index

* @return The Index enumeration value Chinese name

85. */

GetName public static String (int index) {

For (WeekDay weekDay:WeekDay.values ()) {

if (weekday.getindex () = = index)

Weekday.getname return ();

90.}

91.

A. return null;

93.}

94.

@Override.

. Public String toString () {

"WeekDay-" + super.tostring () + "[name=" + this.name

98. + ", val=" + This.val + ", index=" + This.index + "]";

99.}

100.}

101.

102. public static void Main (string[] args) {

103.//Traverse All enumeration values

104. For (WeekDay weekDay:WeekDay.values ()) {

System.out.println (WeekDay);

106.}

107. SYSTEM.OUT.PRINTLN ("************************************");

108.//Convert the string "FRIDAY" to an enumeration type

109. WeekDay WD = weekday.valueof ("FRIDAY");

110.//output converted week's Chinese name, numeric value and custom index value, enumeration value order value, enumeration value name

111. System.out.println ("Chinese name:" + wd.getname ());

SYSTEM.OUT.PRINTLN ("Digital value:" + wd.getval ());

113. SYSTEM.OUT.PRINTLN ("Custom index value:" + wd.getindex ());

SYSTEM.OUT.PRINTLN ("Sequential value:" + wd.ordinal ());

SYSTEM.OUT.PRINTLN ("enumeration value name:" + wd.name ());

System.out.println ("************************************");

117.//Compare two enumeration instances for consistency

118. SYSTEM.OUT.PRINTLN ("Two enumeration instances are consistent:" + wd.equals (weekday.friday));

119.//Compare two enumeration value sizes

System.out.println ("Two enumeration value size:" + WeekDay.MONDAY.compareTo (weekday.friday));

121.}

122.}

Operation Result:

Weekday-monday[name= Monday, val=1, Index=1]

Weekday-tuesday[name= Tuesday, val=2, index=2]

Weekday-wednesday[name= Wednesday, val=3, index=3]

Weekday-thursday[name= Thursday, val=4, index=4]

Weekday-friday[name= Friday, val=5, index=5]

Weekday-saturday[name= Saturday, val=6, index=6]

Weekday-sunday[name= Sunday, val=0, index=7]

************************************

Chinese name: Friday numeric value: 5 Custom Index Value: 5 Order Value: 4 enumeration value name: FRIDAY

************************************

Two enumeration instances are consistent: True two enumeration value size: 4

Use of enumerations in Java

Related Article

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.