JDK1.5,Switch中使用Enum

过往,根据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 only IE should be used but not UserAgent.IE. Let's illustrate both of the above points with a simple (correct) example:


switch (UserAgent.FIREFOX) {
    case IE:
        fail(UserAgent.IE.toString() + " unexpected.");
}
To summarize:


In case statement the enum must be used without brackets. 

In case only the unqualified enum name (like FIREFOX or IE in the above example) must be used.


转自:http://caohongxing7604.blog.163.com/blog/static/32016974200991412040387/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值