用Java编写枚举值表示的语句

Ben*_*key 5 java enums switch-statement

我非常熟悉在其他语言中使用Enums,但我在Java中遇到了一些特殊用途的困难.

Enums的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;
    }

}
Run Code Online (Sandbox Code Playgroud)

因此,代码在switch语句中抱怨"case表达式必须是常量表达式" - 我可以看到为什么编译器可能有问题,因为从技术上讲它们是动态的,但我不知道采取什么方法来解决这个问题.有没有更好的办法?

底线是我需要Enum具有相应的整数值,以便与程序中传入的2D整数数组进行比较.

Gáb*_*tai 5

你可以使用这样的东西:

import java.util.HashMap;
import java.util.Map;

public class MazeNode {

    public enum SlotValue {
        empty(0), start(1), wall(2), visited(3), end(9);

        protected int m_representation;

        SlotValue(int representation) {
            m_representation = representation;

        }

        private static final Map<Integer, SlotValue> mapping = new HashMap<Integer, SlotValue>();

        static {
            for (SlotValue slotValue : SlotValue.values()) {
                mapping.put(slotValue.m_representation, slotValue);
            }
        }

        public static SlotValue fromRepresentation(int representation) {
            SlotValue slotValue = SlotValue.mapping.get(representation);
            if (slotValue == null)
                // throw your own exception
                throw new RuntimeException("Invalid representation:" + representation);
            return slotValue;
        }
    }

    private SlotValue m_mazeNodeSlotValue;

    public MazeNode(SlotValue s) {
        m_mazeNodeSlotValue = s;
    }

    public MazeNode(int s) {
        m_mazeNodeSlotValue = SlotValue.fromRepresentation(s);

    }

    public SlotValue getSlotValue() {
        return m_mazeNodeSlotValue;
    }

    public static void main(String[] args) {
        MazeNode m = new MazeNode(2);
        System.out.println(m.getSlotValue());
        m = new MazeNode(9);
        System.out.println(m.getSlotValue());
    }

}
Run Code Online (Sandbox Code Playgroud)