过往,根据switch的规定,其中可以使用的变量有四种:int,byte,short,char。1.5的新特性支持其中使用Enum作为变量。下面是如何在switch中使用enum。
如何在Switch中使用Enum
当在swtich中使用enum,几乎是很自然的假设他们将被象传统的switch一样被使用。但是,不幸的是,为了适应enums,java不得不加强它的说明文档。enum不同于传统switch的地方主要在两个显著的、非细节方面。
Sun的javac认为:enum的switch中case标签必须是为枚举常量的无限制名称。在他的隐秘的错误信息中,这是不为大多数人所知的。这需要费些时间去理解。
所以,我们采用一些例子来理解这个吧:
switch (UserAgent.FIREFOX) {
case (UserAgent.IE):
fail(UserAgent.IE.toString() + " unexpected.");
}
这看上去显然是对的,不是吗?但是他是错的,在两个方面。
首先case必须没有括号,其次必须使用IE 而不是UserAgent.IE。让我们解释上面得观点,用一个简单的小例子:
switch (UserAgent.FIREFOX) {
case IE:
fail(UserAgent.IE.toString() + " unexpected.");
}
总结:
在case标签中,enum不能使用括号。
在case标签中,只有无限制的枚举名称(像上面的FIREFOX or IE )可以被使用。
附原文如下:
How To Use Enum in Switch
When using enums in a switch, it is almost natural to assume they will be used like a regular switch. Unfortunately to accomodate enums, Java had to enhance its specification and enums in switch behave differently than regular switch statements in two significant and non-trivial ways.
Sun's Javac says -"enum switch case label must be the unqualified name of an enumeration constant. in its cryptic error message. That's probably French to many. I know I had a tough time understanding this statement.
So let's understand this with a simple example:
switch (UserAgent.FIREFOX) {
case (UserAgent.IE):
fail(UserAgent.IE.toString() + " unexpected.");
}
This looks obviously correct doesn't it? Unfortunately it is wrong in two different ways.
Firstly the case should be without the brackets. Secondly on
switch (UserAgent.FIREFOX) {
case IE:
fail(UserAgent.IE.toString() + " unexpected.");
}
To summarize:
In case statement the enum must be used without brackets.
In case on
转自:http://caohongxing7604.blog.163.com/blog/static/32016974200991412040387/