7
enum Color {RED, GREEN, BLUE};
class SwitchEnum
{
  public static void main(String[] args)
  {
    Color c = Color.GREEN;
    switch(c)
    {
      case RED:
        System.out.println("red");
        break;
      case GREEN:
        System.out.println("green");
        break;
      case BLUE:
        System.out.println("blue");
        break;
    }
  }
}

上記のコードは正常にコンパイルされ、期待される出力が得られます。

私の質問は、カラー参照'c'を作成するときに、列挙型の名前(つまり、Color.GREEN)で参照する必要があるのに、ケースブロックでは列挙型の値だけで十分な理由です。すべきではなかった

case Color.RED:

等???

4

3 に答える 3

5

No, it shouldn't. The Java compiler is smart enough to know that you are switching on a Color and so the language allows for this shortcut (and as Paul notes, requires it). In fact, the whole compilation of a switch statement depends on the compiler knowing what you're switching on, since it translates the switch into a jump table based on the index of the enum value you specify. Only very recently have you been able to switch on non-numerical things like a String.

The relevant part of the language spec is in JLS Chapter 14.11:

...
SwitchLabel:
   case ConstantExpression :
   case EnumConstantName :
   default :

EnumConstantName:
   Identifier

If you're looking for insight into why the language was designed the way it was, that's going to be hard to answer objectively. Language design is nuanced, and you have to consider that the assignment syntax was written years and years before enum support was added.

于 2012-05-11T04:11:32.093 に答える
2

It is a language convention. Many different languages have enums, and not all make you do this. In the case of Java, you can do Color.RED or whatever, because of namespaces. By doing so, you can have multiple enums with the same variable names, and they don't clash.

The reason that the switch statement doesn't require you to do Color.RED (and allows you to simply state RED) is that the switch statement knows that it is an enum of type Color, and looks in that namespace.

于 2012-05-11T04:12:24.650 に答える
1

行で

Color c = Color.GREEN;

Javaコンパイラは、宣言()からColor.割り当てられた式()のタイプを推測しないため、これが必要です。同じ理由で、次のように書く必要があります。Color.GREENColor c

ArrayList<String> x = new ArrayList<String>();

単にではありません

ArrayList<String> x = new ArrayList();

(これは実際にはJava 7で部分的に修正されていますが、それは別の話です。)switch(...)ステートメントでは、のタイプはただしcaseのタイプから推測されます。switch

于 2012-05-11T05:25:54.130 に答える