不允许似乎有道理
int a = 8;
boolean b = (boolean)a;
因为这可能会导致程序员错误,因为即使是整数,生成的 boolean 值也会是假的,但为什么扩大强制转换,例如int a = true
工作?
编辑:
根据 JVM 规范,第 3.3.4 节:
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.
例如:
public static boolean returnFalse() {
return false;
}
public static boolean returnTrue() {
return true;
}
编译为:
public static boolean returnFalse();
Code:
0: iconst_0
1: ireturn
public static boolean returnTrue();
Code:
0: iconst_1
1: ireturn
最佳答案
内部表示不相关。
Java 是强类型的:int
不是boolean
,boolean
也不是int
.
这是一个设计决定——如果你想使用 true/false,使用 boolean 值;传达一些东西。
如果您想使用整数来表示真/假,请使用数学比较——这也很好。
该语言不支持直接转换,因为它在设计上不支持。
关于JVM规范和 boolean 值的内部表示,这句话很有意思:
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.
对我来说,那是:
If the compiler/VM is using a VM integer to represent true/false, then it must use the 1/0 convention. With the implication being: If the compiler/VM isn't using a VM integer for true/false, this isn't a requirement.
对这一点的澄清会很有趣,但最终不相关,真的。
关于java - 为什么 boolean 是唯一没有定义强制或转换的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10954709/