在我看来,有两种解决方案:
1)您可以通过Java中的类模拟“C枚举类型”:
class Animals {
public static int DOG = 0;
public static int CAT = 1;
public static int MOUSE = 2;
}
在这种情况下,您需要手动为枚举设置值 - 在 C 中,编译器会自动完成此操作。
枚举的使用方式如下:
public class Test {
public static void main(String[] args) {
int[] age = new int[3];
age[Animals.DOG] = 4;
age[Animals.CAT] = 3;
age[Animals.MOUSE] = 10;
for (int i = 0; i < age.length; i++) {
System.out.print(age[i] + " ");
}
}
}
我认为这是一个不好的解决方案,因为它违反了面向对象编程原则中的封装性(在Animals类中)。
2)您可以使用Java枚举。
enum Animals {
DOG(0), CAT(1), MOUSE(2);
int value;
private Animals(int value) {
this.value = value;
}
public int getValue() {
return this.value;
}
}
使用示例
public class Test {
public static void main(String[] args) {
int[] age = new int[3];
age[Animals.DOG.getValue()] = 4;
age[Animals.CAT.getValue()] = 3;
age[Animals.MOUSE.getValue()] = 10;
for (int i = 0; i < age.length; i++) {
System.out.print(age[i] + " ");
}
}
}
在Java中,枚举是一种类。要了解更多细节,请阅读this。
枚举没有默认值,您必须自己设置。在此示例中,使用构造函数Animal(int value)
完成。此外,我们不能像整数值一样使用Animals.DOG
,而必须使用方法getValue()
。
Map
和List
? - user1907906