Skip to content

Conversation

@Silverados
Copy link
Contributor

原文为
The Java Virtual Machine does directly support boolean arrays. Its newarray
instruction (§newarray) enables creation of boolean arrays. Arrays of type
boolean are accessed and modified using the byte array instructions baload and
bastore (§baload, §bastore).

https://docs.oracle.com/javase/specs/jvms/se8/jvms8.pdf 第10页

原文为 The Java Virtual Machine does directly support boolean arrays. Its newarray instruction (§newarray) enables creation of boolean arrays. Arrays of type boolean are accessed and modified using the byte array instructions baload and bastore (§baload, §bastore).
@CyC2018
Copy link
Owner

CyC2018 commented Mar 18, 2019

@Silverados

The Java Virtual Machine encodes boolean array components using 1 to represent
true and 0 to represent false. Where Java programming language boolean values
are mapped by compilers to values of Java Virtual Machine type int, the compilers
must use the same encoding.

@Silverados
Copy link
Contributor Author

在编译层面,JVM直接支持boolean数组,包括指令§newarray,§baload, §bastore。但是在这些boolean数组里仍然是用int的 0或1 来表示 false或true。

这是一段简单的代码:

public static void main(String[] args){ boolean bool = true; boolean[] boolArray = new boolean[2]; int[] intArray = new int[2]; bool = false; boolArray[0] = true; boolArray[1] = false; }

用javap -v 反编译,其中对应的一段为(注释不太流畅,理解那个意思就行了哈哈):

public static void main(java.lang.String[]); descriptor: ([Ljava/lang/String;)V flags: ACC_PUBLIC, ACC_STATIC Code: stack=3, locals=4, args_size=1 0: iconst_1 // 将int 类型的1放入操作数栈 1: istore_1 // 将栈顶(1)弹出存入局部变量表1位置 2: iconst_2 // 将int 类型的2放入操作数栈 3: newarray boolean // 创建一个大小为2的数组,这个数组是boolean类型的 5: astore_2 // 将数组存入局部变量表2位置 6: iconst_2 // 将int 类型的2放入操作 7: newarray int // 创建一个大小为2的数组,这个数组是int类型的 9: astore_3 // 将数组存入局部变量表3位置 10: iconst_0 // 将int 类型的0放入操作数栈 11: istore_1 // 将栈顶(0)弹出存入局部变量表1位置 12: aload_2 13: iconst_0 // 将局部变量表2(boolean 数组)下标为0的元素放入操作数栈 14: iconst_1 // 将int 类型的1放入操作数栈 15: bastore // 放回局部变量表,此时0下标值为1了 16: aload_2 // 17: iconst_1 // 18: iconst_0 // 19: bastore // 同理,1下标的值变成0了 20: return // 结束 

可以看到指令集§newarray,§baload, §bastore都被使用。在赋值上使用的则是 iconst_0或 iconst_1。

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

newarray! 如果merge的话注意改一下。

@Silverados Silverados closed this Mar 26, 2019
@Silverados Silverados deleted the patch-5 branch March 26, 2019 05:25
@Silverados Silverados restored the patch-5 branch March 26, 2019 05:33
@Silverados Silverados reopened this Mar 26, 2019
@CyC2018 CyC2018 merged commit f410541 into CyC2018:master Mar 26, 2019
@CyC2018
Copy link
Owner

CyC2018 commented Mar 26, 2019

@Silverados 准确来讲你的理解没错,但是考虑到这篇文章主要讲 Java 基础,涉及太多虚拟机底层编译细节的话会对一些人造成困惑,所以就去掉了编译指令。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

2 participants