开发者

using enum inside a switch

Can we use enum insid开发者_如何学Pythone a switch?

public enum Color {
  RED,BLUE,YELLOW


}


 public class Use {
  Color c = Color.BLUE;

  public void test(){
      switch(c){
      case Color.BLUE:

      }
  }
}

I am getting some error in this.

The enum constant Color.BLUE reference cannot be qualified in a case label  Use.java        line 7  Java Problem


case COLOR.BLUE:

    }

In the above code instead of COLOR.BLUE only write BLUE


E.G.

import java.awt.Color;

class ColorEnum {

    enum Color{BLUE,RED,YELLOW};

    public static void main(String[] args) {
        Color c = Color.BLUE;
        switch(c) {
            case BLUE:
                System.out.println("Blue!");
                break;
            case RED:
                System.out.println("Red!");
                break;
            case YELLOW:
                System.out.println("Yellow!");
                break;
            default:
                System.out.println("Logic error!");
        }
    }
}


Write it like this:

public void test(){
  switch(c) {
  case BLUE:

  }
}

The enum label MUST NOT be qualified when used as a case label. The grammar at JLS 14.11 says this:

SwitchLabel:
    case ConstantExpression :
    case EnumConstantName :
    default :

EnumConstantName:
    Identifier

Note that a simple identifier is require, not an identifier qualified by the enum name.

(I don't know why they designed the syntax like that. Possibility it was to avoid some ambiguity in the grammar. But either way, that's the way it is.)


Why use a switch at all? Rather just let the enum hold the Color information itself (encapsulate it) and thereby do all the dirty work. The advantage to this, is if you change your enum, you don't have to root through all code that uses it, changing all switch statements. For instance:

import java.awt.Color;

public enum MyColor {
   RED("Red", Color.red), BLUE("Blue", Color.blue), 
   YELLOW("Yellow", Color.yellow);

   private String text;
   private Color color;
   private MyColor(String text,Color color) {
      this.text = text;
      this.color = color;
   }

   public String getText() {
      return text;
   }

   public Color getColor() {
      return color;
   }

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

and an example of how this can be used is as follows:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

@SuppressWarnings("serial")
class MyColorTest extends JPanel {
   private static final Dimension PREF_SIZE = new Dimension(400, 300);

   public MyColorTest() {
      for (final MyColor myColor : MyColor.values()) {
         add(new JButton(new AbstractAction(myColor.getText()) {
            @Override
            public void actionPerformed(ActionEvent arg0) {
               MyColorTest.this.setBackground(myColor.getColor());
            }
         }));

      }
   }

   @Override
   public Dimension getPreferredSize() {
      return PREF_SIZE;
   }

   private static void createAndShowUI() {
      JFrame frame = new JFrame("MyColorTest");
      frame.getContentPane().add(new MyColorTest());
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      java.awt.EventQueue.invokeLater(new Runnable() {
         public void run() {
            createAndShowUI();
         }
      });
   }

}


Yes, you can use enums in switch statements, but make sure not to use FQCN (fully-Qualified Class Name) in case labels.


Following is extracted from "enum constant reference cannot be qualified in a case label of switch statement"

In Short

When a Java switch statement uses an enum parameter; qualified names of the enum values should not be used in case labels, but only the unqualified names; then switch statement will consider all the labels are referring to the enum type that is used as the parameter.

Why only unqualified values?

If qualified references were allowed for case labels; there would be no means to restrict the enum type used in the labels to be same as the parameter type of switch statement.

public enum Status {
    REGISTERED,
    TERMINATED
}

public class TestStatus {
    public static String getMessage(Status status) {
        String message;
        switch (status) {
            // case Status.REGISTERED: // line 1
            case REGISTERED: // line 2
                message = "Welcome";
                break;
            default:
                message = "Good bye";
                break;
        }
    return message;
}


enum MyEnum{
    A,B,C

    MyEnum(){
        switch(this){
            case A:
                 //....
                 break;
            case B:
                 //....
                 break;
            case C:
                 //....
                 break;
        }
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜