在 Java 中,所有数字类型都从 java.lang.Number 扩展而来。有一个类似以下的方法是不是一个好主意:
public boolean areEqual(Number first, Number second) {
if (first != null && second != null) {
return first.equals(second);
}
}
我担心双 2.00000 不等于 int 2 的情况。这些是否由内置的 equals 处理?如果没有,有没有办法在java中编写一个简单的数字比较函数? (apache commons等外部库都可以)
最佳答案
Double
是 NEVER equals
为 Integer
。此外,double
与 Double
不同。
Java 有原始类型和引用类型。 Java 中真正的数字类型不是从 Number
扩展而来的,因为它们是原语。
您可能需要考虑一个不混合类型的系统,因为这通常会给隐式/显式转换带来很多麻烦,可能/可能不会丢失信息等。
相关问题
关于 int
与 Integer
:
关于编号
比较:
另见
- Java Language Guide/Autoboxing
- JLS 4.2 4.2 Primitive Types and Values
The numeric types are the integral types and the floating-point types. The integral types are
byte
,short
,int
, andlong
andchar
. The floating-point types arefloat
anddouble
.
关于混合类型的计算
混合类型计算是 Java Puzzlers 中至少 4 个谜题的主题。 .
以下是各种摘录:
it is generally best to avoid mixed-type computations [...] because they are inherently confusing [...] Nowhere is this more apparent than in conditional expressions. Mixed-type comparisons are always confusing because the system is forced to promote one operand to match the type of the other. The conversion is invisible and may not yield the results that you expect
Prescription: Avoid computations that mix integral and floating-point types. Prefer integral arithmetic to floating-point.
关于java - 比较Java中的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3214448/