Java 和开关盒

标签 java

有谁知道为什么 Java 不允许您打开大于整数的数字?这背后有什么技术原因吗?

最佳答案

如前所述here , switch 适用于 byte、short、char 和 int 原始数据类型。它还适用于枚举类型和一些“包装”某些基本类型的特殊类:Character、Byte、Short 和 Integer。

Java switch语句被编译成JVM bytecode tableswitch or lookupswitch .这两种字节码都要求大小写值是唯一的、32 位、整数、编译时常量。

tableswitch 和 lookupswitch 指令均包含一个默认分支偏移量和一组可变长度的 case 值/分支偏移量对。
两条指令都从堆栈中弹出键(紧跟在 switch 关键字后面的括号中的表达式的值)。
键与所有大小写值进行比较:

  • 如果找到匹配项,则采用与案例值关联的分支偏移量。
  • 如果未找到匹配项,则采用默认分支偏移量。

尽管上面代表了实现细节,但我相信用于 switch 的类型是与控制流的高效字节码兼容的类型,并且它可能是一个重要的部分,因此选择。

如本Java Bug所述:

I suppose you could allow Java switch statement cases to include other types of values, and compile a switch statement that uses one of those kinds of values into other bytecode, such as a sequence of ifs and gotos. But then we'd have to examine all switch statements carefully in order to determine if it will be compiled into a fast switch bytecode or a slow sequence of if-elses.

如其他 Java bug 中所述

'switch' statements can use function-table dispatch and/or binary-tree search to match the case statements faster than just testing them one by one in order.

关于Java 和开关盒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/308224/

相关文章:

java - 如何计算代码路径中的指令数量?

从文件读取时出现 java.util.InputMismatchException 错误,类型有什么问题?

java - Spring webapp 显示数据库中的动态内容

java - Birt报表-IReportEngineFactory为空

java - 莫基托 : mock() calls real method

java - 使用 OpenCV/JavaCV 的透视图像

java - @RequestBody 在发出 POST 请求时给出空的 JsonObject

java - super (空): what does this mean?

java - 寻找服务器发送事件规范客户端的 Java 实现。

java - 在 JPQL 中迭代集合