为什么Java不支持无符号整数?

在我看来,这是一个奇怪的遗漏,因为它们允许人们编写不太可能在意外的大输入上产生溢出的代码。

此外,使用无符号整数可以是一种自我文档的形式,因为它们表明无符号整型所要保存的值永远不应该是负数。

最后,在某些情况下,无符号整数对于某些运算(如除法)更有效。

包含这些的缺点是什么?


当前回答

Java确实有unsigned类型,或者至少有一个:char是一个unsigned short类型。所以不管高斯林找什么借口,他都不知道为什么没有其他无符号类型。

还有短型:短型一直被用于多媒体。原因是您可以在一个32位无符号长函数中拟合2个样本,并向量化许多操作。8位数据和无符号字节也是如此。你可以在一个寄存器中放入4或8个样本进行向量化。

其他回答

一旦有符号整型和无符号整型混合在表达式中,事情就开始变得混乱,你可能会丢失信息。将Java限制为有符号int型只能真正解决问题。我很高兴我不必担心整个有符号/无符号的问题,尽管我有时会错过字节中的第8位。

http://skeletoncoder.blogspot.com/2006/09/java-tutorials-why-no-unsigned.html

这个家伙说,因为C标准定义了包含无符号整型和有符号整型的操作被视为无符号整型。这可能导致负符号整数滚动到一个大的无符号整数,可能会导致错误。

Java确实有unsigned类型,或者至少有一个:char是一个unsigned short类型。所以不管高斯林找什么借口,他都不知道为什么没有其他无符号类型。

还有短型:短型一直被用于多媒体。原因是您可以在一个32位无符号长函数中拟合2个样本,并向量化许多操作。8位数据和无符号字节也是如此。你可以在一个寄存器中放入4或8个样本进行向量化。

I once took a C++ course with someone on the C++ standards committee who implied that Java made the right decision to avoid having unsigned integers because (1) most programs that use unsigned integers can do just as well with signed integers and this is more natural in terms of how people think, and (2) using unsigned integers results in lots easy to create but difficult to debug issues such as integer arithmetic overflow and losing significant bits when converting between signed and unsigned types. If you mistakenly subtract 1 from 0 using signed integers it often more quickly causes your program to crash and makes it easier to find the bug than if it wraps around to 2^32 - 1, and compilers and static analysis tools and runtime checks have to assume you know what you're doing since you chose to use unsigned arithmetic. Also, negative numbers like -1 can often represent something useful, like a field being ignored/defaulted/unset while if you were using unsigned you'd have to reserve a special value like 2^32 - 1 or something similar.

Long ago, when memory was limited and processors did not automatically operate on 64 bits at once, every bit counted a lot more, so having signed vs unsigned bytes or shorts actually mattered a lot more often and was obviously the right design decision. Today just using a signed int is more than sufficient in almost all regular programming cases, and if your program really needs to use values bigger than 2^31 - 1, you often just want a long anyway. Once you're into the territory of using longs, it's even harder to come up with a reason why you really can't get by with 2^63 - 1 positive integers. Whenever we go to 128 bit processors it'll be even less of an issue.

在JDK8中,它确实提供了一些支持。

尽管有Gosling的担忧,但我们仍然可能看到Java对unsigned类型的完全支持。