In Java, all numeric types extend from java.lang.Number. Would it be a good idea to have a method like the following:
public boolean areEqual(Number first, Number second) {
if (first != null && second != null) {
return first.equals(second);
}
}
I’m concerned about cases where a double 2.00000 does not equal an int 2. Are these handled by the built-in equals? If not, is there any way to write a simple number compare function in java? (external libraries such as apache commons are ok)
A
Doubleis NEVERequalsto anInteger. Moreover, adoubleis not the same as aDouble.Java has primitive types and reference types. The truly numeric types in Java do not extend from
Number, because they’re primitives.You may want to consider a system where you’re not mixing types, because that usually will cause a lot of trouble with implicit/explicit conversions that may/may not lose information, etc.
Related questions
On
intvsInteger:On
Numbercomparison:java.lang.NumberimplementComparable?See also
On mixed-type computation
Mixed-type computation is the subject of at least 4 puzzles in Java Puzzlers.
Here are various excerpts: