开发者

Switch statement: number to enum value / 1002 = MyEnum.NewYorkID

Well, I want to make this work

public static void main(String[] args) {

    int cityId = 1234;

    switch (cityId) {
开发者_开发技巧        case MOSCOW:
            System.out.println("Moscow");
            break;

        case SOCHI:
            break;  
}

public enum Test {
    MOSCOW,
    NEWYORK,
    SOCHI
}

So I want to link Test enum with city ids, is that possible? What is the best pattern for this situation?

Thank you!


You can't mix that in a switch. Either you pass a Test enum into the switch statement, or use the constant ids in the case statements.

I'd suggest having a mapping cityId <-> Test instance and converting before calling the switch.

Something like

Map<Integer, Test>` mapping = ...;
mapping.put(1234, Test.MOSCOW ); //note the use of autoboxing

...

mapping.get(cityId); //note the use of autoboxing

Edit: note that you could put this mapping into the enum, add a cityId field to the enum and automatically fill the mapping from the array returned by values(), much like Chris' suggestion.

public enum Test {
   MOSCOW(1001),
   NEWYORK(1002),
   SOCHI(1234);

   private final int cityId;

   private Test(int cityId) {
    this.cityId = cityId;
   }

   ...


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

   static { //executed when the class is loaded
     for( Test t : values() ) {
        mapping.put(t.getCityId(), t);
     }
   }

   public static toTest(int cityId) {
     return mapping.get(cityId);
   }
}

That's something we often do for similar things.


The only problem with your code is that you need to switch on Test not int.

ie:

public static void main(String[] args) {

    Test city = SOCHI;

    switch (city) {
        case MOSCOW:
            System.out.println("Moscow");
        break;

       case SOCHI:
           break;   
}

public enum Test{
    MOSCOW,
    NEWYORK,
    SOCHI
}


You can add a cityId field in your enum:

public enum Test {
    MOSCOW(1001),
    NEWYORK(1002),
    SOCHI(1234);

    private final int cityId;

    private Test(int cityId) {
        this.cityId = cityId;
    }

    public int getCityId() {
        return cityId;
    }

    public static Test valueOf(int cityId) {
        /*
         * Using linear search because there's only a small handful
         * of enum constants. If there's a huge amount (say, >20),
         * a map lookup is better.
         */
        for (Test value : values()) {
            if (value.cityId == cityId)
                return value;
        }
        throw new IllegalArgumentException("Unknown city ID: " + cityId);
    }
}

Then you can indeed switch on the enum value:

switch (Test.valueOf(cityId)) {
case MOSCOW:
    // ...
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜