Sangli
Sangli

Reputation: 363

Compiler error for string switch case label

I have a switch case label for the enum constants. My Enum and case label example is as follows :

private Enum PreferenceType {
   FIRST,SECOND,THIRD;

   private String prefKey;

   PreferenceType(String prefKey) {
      this.prefKey = prefKey;
   }

   @Override
   public String toString() {
      return prefKey;
   } 
}

private String getPreference() {
   switch(getMessage())
   {
    case PreferenceType.FIRST.toString():
       //do something;
       break;

    case PreferenceType.SECOND.toString():
       //do something;
       break;

    case PreferenceType.THIRD.toString():
       //do something;
       break;
    default: break;
    }
 }

The whole case label statement is marked in red line by eclipse "case PreferenceType.FIRST.toString():" and when I hover the mouse over the case label the error says "case expressions must be constant expressions". My jdk is of version 1.7 and my eclipse is of version 3.7.2. Can someone please tell me how do I resolve this issue?

Upvotes: 0

Views: 1532

Answers (2)

Jason
Jason

Reputation: 11822

You can switch on an enumeration, but you cannot switch on a String.

Try:

private Enum PreferenceType {
    FIRST("key1"),SECOND("key2"),THIRD("key3");

    static Map<String, PreferenceType> prefMap = new HashMap<String, PreferenceType>();

    private String prefKey;

    PreferenceType(String prefKey) {
        this.prefKey = prefKey;
        prefMap.put(prefKey, this);
    }

    @Override
    public String toString() {
        return prefKey;
    }

    public static PreferenceType getPreferenceTypeFor(final String key) {
        return prefMap.get(key);
    } 
}

and the switch should be...

switch(PreferenceType.getPreferenceTypeFor(getMessage()))

and your case statements would be...

case PreferenceType.FIRST:
    //do something;
break;

case PreferenceType.SECOND:
    //do something;
break;

case PreferenceType.THIRD:
    //do something;
break;

Now when you call PreferenceType.getPreferenceTypeFor("key1") you will get PreferenceType.FIRST which can then be used in the switch.

Upvotes: 1

josephus
josephus

Reputation: 8304

The error message says it all -- case expressions must be constant expressions

You're using the return value of the toString() method, which, as far as the compiler is concerned, is NOT CONSTANT.

Upvotes: 1

Related Questions