我非常熟悉在其他语言中使用 Enums,但是我在 Java 中遇到了一些特殊用途的困难。
枚举的 Sun 文档大胆地指出:
“Java 编程语言的枚举比它们在其他语言中的对应物强大得多,它们只不过是美化的整数。”
好吧,这很花哨,但出于在 switch 语句中进行比较的原因,我需要为每个枚举提供一个常量数据类型表示。情况如下:我正在构建将代表给定空间的节点,或迷宫图中的“槽”,并且这些节点必须能够从代表迷宫的 2D 整数数组构造。这是我为 MazeNode 类获得的内容,目前是问题所在(switch 语句吠叫):
注意:由于 case 语句中的动态项,我知道此代码不起作用。它是为了说明我所追求的。
public class MazeNode
{
public enum SlotValue
{
empty(0),
start(1),
wall(2),
visited(3),
end(9);
private int m_representation;
SlotValue(int representation)
{
m_representation = representation;
}
public int getRepresentation()
{
return m_representation;
}
}
private SlotValue m_mazeNodeSlotValue;
public MazeNode(SlotValue s)
{
m_mazeNodeSlotValue = s;
}
public MazeNode(int s)
{
switch(s)
{
case SlotValue.empty.getRepresentation():
m_mazeNodeSlotValue = SlotValue.start;
break;
case SlotValue.end.getRepresentation():
m_mazeNodeSlotValue = SlotValue.end;
break;
}
}
public SlotValue getSlotValue()
{
return m_mazeNodeSlotValue;
}
}
所以代码用“case 表达式必须是常量表达式”来抱怨 switch 语句——我可以理解为什么编译器可能会遇到问题,因为从技术上讲它们是动态的,但我不确定采取什么方法来解决这个问题。有没有更好的办法?
底线是我需要 Enum 具有相应的整数值,以便与程序中传入的 2D 整数数组进行比较。