为什么Java不允许转换布尔值 - > Int? [英] Why Doesn't Java Allow Casting Boolean -> Int?

查看:611
本文介绍了为什么Java不允许转换布尔值 - > Int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么Java不允许从布尔值转换为int,如下所示:

I was wondering why Java doesn't allow casting from a boolean to an int, like so:

boolean foo = true;
int bar = (int)foo;

这可以在一行代码中完成,例如

This can be done in one line of code, for example,

bar = foo ? 1 : 0;

但看起来像一个更好,更容易读的方法是允许类型转换,与 double int 一样。为什么Java不包括这个特性?

but it seems like an better and easier-to-read way would be to allow type-casting, as with double and int. Why doesn't Java include this feature?

推荐答案

它不允许这样,因为Java设计者在C和C ++中的布尔/整数重载是一个重要的错误源。

It doesn't allow this because the Java designers (correctly) recognized that the boolean / integer overloading in C and C++ was a significant source of errors.

(我记得在写作中有些设计原理,但我找不到它。 )

(I recall seeing that in writing in some design rationale, but I can't find it.)

例如:

if (i = 0) {
    ...
}

是合法的,但可能是C或C ++。

is legal but probably a bug in C or C++.

Java通过使 boolean 和不能从一个转换为另一个类型的整数数据类型避免此问题和其他问题另一个。因此,上面是Java中的编译错误。

Java avoid this and other problems by making boolean and the integer datatypes different types that cannot be converted from one to the other. Thus, the above is a compilation error in Java.

现在这不能解释为什么你不能显式地 type cast a boolean int 。但我认为可以通过观察以下内容来理解:

Now this doesn't explain why you cannot explicitly type cast a boolean to an int. But I think that can be understood by observing the following:


  • 您很少需要在真实的Java程序中。

  • You rarely need to do that in real Java programs.

数字< - >布尔类型转换不会像其他类型转换那样工作。特别是,对于其他类型,有up-cast和down-casts,并且在Java中的上传 1 不需要显式类型转换。

Number <-> boolean casting wouldn't jell with the way that other type casts work. In particular, for other types there are up-casts and down-casts, and up-casts1 in Java don't require an explicit type cast.

您不能在数字和字符串之间,或在字符串之间类型转换其他对象。这些是转换,而不是类型转换。

You can't typecast between numbers and string either, or between strings an other objects. These are conversions, not type casts. And int <-> boolean is too.

1 - 我在这里(故意)使用我的术语。正确的Java术语是加宽和缩小。缩小转换需要一个明确的类型转换,字面值有一个有限的异常。扩大转化次数不需要转换类型。

这篇关于为什么Java不允许转换布尔值 - &gt; Int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆