这个功能会被放到后面的Java版本中吗?
有人能解释一下为什么我不能这样做,比如,Java的switch语句工作的技术方式吗?
这个功能会被放到后面的Java版本中吗?
有人能解释一下为什么我不能这样做,比如,Java的switch语句工作的技术方式吗?
当前回答
基于整数的开关可以优化为非常高效的代码。基于其他数据类型的开关只能编译为一系列if()语句。
因此,C和c++只允许对整型进行切换,因为它对其他类型没有意义。
c#的设计者认为风格很重要,即使它没有什么优势。
Java的设计者显然和C的设计者思想相似。
其他回答
多年来,我们一直在为此使用(n个开源)预处理器。
//#switch(target)
case "foo": code;
//#end
预处理文件被命名为Foo.jpp,并使用ant脚本处理为Foo.java。
优点是它被处理成运行在1.0上的Java(尽管通常我们只支持1.4版本)。而且,与使用枚举或其他变通方法相比,这样做(大量字符串开关)要容易得多——代码更容易阅读、维护和理解。IIRC(在这一点上不能提供统计数据或技术推理)也比自然的Java等价物更快。
缺点是你没有编辑Java,所以它有更多的工作流(编辑、处理、编译/测试),加上IDE将链接回Java,这有点复杂(切换变成一系列if/else逻辑步骤),并且切换case顺序没有维护。
对于1.7以上版本,我不推荐使用它,但如果您想编写针对早期jvm的Java程序,它很有用(因为Joe public很少安装最新版本)。
您可以从SVN获取或在线浏览代码。您将需要EBuild按原样构建它。
James Curran简洁地说:“基于整数的开关可以优化为非常高效的代码。基于其他数据类型的开关只能编译为一系列if()语句。因此,C和c++只允许在整数类型上切换,因为这对其他类型是没有意义的。”
My opinion, and it's only that, is that as soon as you start switching on non-primitives you need to start thinking about "equals" versus "==". Firstly comparing two strings can be a fairly lengthy procedure, adding to the performance problems that are mentioned above. Secondly if there is switching on strings there will be demand for switching on strings ignoring case, switching on strings considering/ignoring locale,switching on strings based on regex.... I would approve of a decision that saved a lot of time for the language developers at the cost of a small amount of time for programmers.
从1.7开始直接使用String的例子如下:
public static void main(String[] args) {
switch (args[0]) {
case "Monday":
case "Tuesday":
case "Wednesday":
System.out.println("boring");
break;
case "Thursday":
System.out.println("getting better");
case "Friday":
case "Saturday":
case "Sunday":
System.out.println("much better");
break;
}
}
在Java 11+中,变量也是可行的。唯一的条件是它必须是常数。
例如:
final String LEFT = "left";
final String RIGHT = "right";
final String UP = "up";
final String DOWN = "down";
String var = ...;
switch (var) {
case LEFT:
case RIGHT:
case DOWN:
default:
return 0;
}
PS.我还没有在早期的jdk中尝试过这一点。所以请更新答案,如果它也支持。
下面是一个基于JeeBee的帖子的完整示例,使用java枚举而不是使用自定义方法。
注意,在Java SE 7及更高版本中,您可以在switch语句的表达式中使用String对象。
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
String current = args[0];
Days currentDay = Days.valueOf(current.toUpperCase());
switch (currentDay) {
case MONDAY:
case TUESDAY:
case WEDNESDAY:
System.out.println("boring");
break;
case THURSDAY:
System.out.println("getting better");
case FRIDAY:
case SATURDAY:
case SUNDAY:
System.out.println("much better");
break;
}
}
public enum Days {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY
}
}