How does Java#39;s switch work under the hood?(Java 的 switch 在底层是如何工作的?)
问题描述
Java 的 switch 语句在底层是如何工作的?它如何将正在使用的变量的值与案例部分中给出的值进行比较?它是使用 ==
还是 .equals()
,还是完全是别的东西?
How does Java's switch statement work under the hood? How does it compare the value of the variable being used, to those given in the case parts? Does it use ==
or .equals()
, or is it something else entirely?
我主要对 1.7 之前的版本感兴趣.
I'm mainly interested in the pre 1.7 versions.
推荐答案
两者都没有. 它使用 lookupswitch
JVM指令,本质上是查表.看一下下面例子的字节码:
Neither. it uses the lookupswitch
JVM instruction, which is essentially a table lookup. Take a look at the bytecode of the following example:
public static void main(String... args) {
switch (1) {
case 1:
break;
case 2:
break;
}
}
public static void main(java.lang.String[]);
Code:
Stack=1, Locals=1, Args_size=1
0: iconst_1
1: lookupswitch{ //2
1: 28;
2: 31;
default: 31 }
28: goto 31
31: return
这篇关于Java 的 switch 在底层是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java 的 switch 在底层是如何工作的?


基础教程推荐
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 降序排序:Java Map 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01