Java 中可以将整数作为枚举的元素吗?

java 8object oriented programmingprogramming更新于 2025/9/21 5:00:17

Java 中的枚举 (enum) 是一种存储一组常量值的数据类型。您可以使用枚举来存储固定值,例如一周中的天数、一年中的月份等。

您可以使用关键字 enum 定义枚举,后跟枚举名称 −

enum Days {
   SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}

与数组一样,枚举中的元素/常量使用从 0 开始的数字进行标识,在上面的示例中,日期使用数字进行标识,如下图所示 −

整数作为枚举的元素

不,枚举中只能有字符串作为元素。在其中使用字符串会产生编译时错误。

示例

在下面的 java 示例中,我们尝试将 3 个整数值作为枚举的元素。

enum EnumTest {
   10024, 5336, 9987
}

输出

EnumTest.java:1: error: <identifier> expected
   enum EnumTest {
               ^
EnumTest.java:2: error: ',', '}', or ';' expected
   10024, 5336, 9987
   ^
EnumTest.java:2: error: '}' expected
   10024, 5336, 9987
      ^
3 errors

相反,您可以将整数值赋给枚举的元素。

示例

enum StudentMarks {
   //具有值的常量
   Krishna(86), Katyayani(75), Bhanu(89), Bhargav(70), Lata(90);
   //实例变量
   private int marks;
   //用于初始化实例变量的构造函数
   StudentMarks(int marks) {
      this.marks = marks;
   }
   public static void getMarks(int model){
      StudentMarks marks[] = StudentMarks.values();
      System.out.println("Price of: "+marks[model]+" is "+marks[model].marks);
   }
}
public class Sample{
   public static void main(String args[]){
      StudentMarks m[] = StudentMarks.values();
      for(int i = 0; i<m.length; i++ ) {
         StudentMarks.getMarks(i);
      }
   }
}

输出

Price of: Krishna is 86
Price of: Katyayani is 75
Price of: Bhanu is 89
Price of: Bhargav is 70
Price of: Lata is 90

相关文章