【发布时间】:2014-11-03 00:56:05
【问题描述】:
对于下面的TypeAndSize类,
class TypeAndSize {
Species type; // runType EMPTY, SHARK, or FISH
int size; // Number of cells in the run for that runType.
enum Species{EMPTY,SHARK,FISH}
/**
* Constructor for a TypeAndSize of specified species and run length.
* @param species is Ocean.EMPTY, Ocean.SHARK, or Ocean.FISH.
* @param runLength is the number of identical cells in this run.
* @return the newly constructed Critter.
*/
TypeAndSize(Species species, int runLength) {
if (species == null) {
System.out.println("TypeAndSize Error: Illegal species.");
System.exit(1);
}
if (runLength < 1) {
System.out.println("TypeAndSize Error: runLength must be at least 1.");
System.exit(1);
}
this.type = species;
this.size = runLength;
}
}
在下面的代码中使用enum类类型的成员字段,
class RunLengthEncoding {
...
public RunLengthEncoding(int i, int j, int starveTime) {
this.list = new DList2();
this.list.insertFront(TypeAndSize.Species.EMPTY, i*j);
....
}
...
}
让我问这个问题。
我的问题:
为什么enum 类的成员字段设计为enum 的实例?因为enum 类类型的参数易于传递,它可以向后兼容C 语言中enum 的旧概念,它是一个常量的集合?是这个原因吗?
【问题讨论】:
-
我不太明白你在说什么。您是否将 java 的枚举与 C 风格的一切可见类型进行比较(只需输入
EMPTY)? -
没有
enumpre 5.0 -
@Pokechu22 是的,这是正确的
-
基本上是类型安全,C 中的常量(只是整数)不提供。
-
您在问“为什么枚举类的成员字段被设计为枚举的实例”,但在您的代码中,我看不到任何您试图演示的内容。