Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch Statement for Enum Value Representations in Java

I'm very familiar with using Enums in other languages, but I'm having some difficulty in Java with a particular use.

The Sun documentation for Enums boldly states:

"Java programming language enums are far more powerful than their counterparts in other languages, which are little more than glorified integers."

Well, that's dandy, but I kind of need to have a constant datatype representation for each of the Enums, for comparison reasons in a switch statement. The situation is as follows: I'm constructing nodes which will represent a given space, or 'slot' in a maze graph, and these nodes must be able to be constructed from a 2D integer array which represents the maze. Here's what I've got for the MazeNode class, which is currently where the problem is (the switch statement barks):

NOTE: I know this code does not function, due to the dynamic item in the case statement. It is there to illustrate what I'm after.

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

}

So the code complains on the switch statement with "case expressions must be constant expressions" -- I can see why the compiler might have trouble, since technically they are dynamic, but I'm not sure what approach to take to resolve this. Is there a better way?

The bottom line is I need the Enum to have corresponding integer values for comparison against the incoming 2D array of integers in the program.

like image 852
dreadwail Avatar asked Jun 27 '09 06:06

dreadwail


People also ask

Can you use a switch statement for enums?

We can use also use Enum keyword with Switch statement. We can use Enum in Switch case statement in Java like int primitive.

Can we change value of enum in Java?

Enum constants are implicitly static and final and you can not change their value once created. Enum in Java provides type-safety and can be used inside switch statements like int variables.

Can enum type can be passed as an argument to switch statement?

Yes, You can use Enum in Switch case statement in Java like int primitive. If you are familiar with enum int pattern, where integers represent enum values prior to Java 5 then you already knows how to use the Switch case with Enum.

What is switch () in Java?

The switch case in java executes one statement from multiple ones. Thus, it is like an if-else-if ladder statement. It works with a lot of data types. The switch statement is used to test the equality of a variable against several values specified in the test cases.


1 Answers

You can use something like this:

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());
    }

}
like image 174
Gábor Hargitai Avatar answered Sep 29 '22 08:09

Gábor Hargitai