我们是否可以在 Java 中将整数作为枚举元素?
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 {
//Constants with values
Krishna(86), Katyayani(75), Bhanu(89), Bhargav(70), Lata(90);
//Instance variable
private int marks;
//Constructor to initialize the instance variable
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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
安卓
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP