是否存在数字“值等于"? [英] Is there a number "value equals"?
问题描述
默认情况下,Java会 Binary Numeric Promotion (原始数字),但是对对象却没有做同样的事情.这是演示的快速测试:
By default, Java does Binary Numeric Promotion for primitives, but does not do the same thing for objects. Here's a quick test to demonstrate:
public static void main(String... args) {
if(100 == 100L) System.out.println("first trial happened");
if(Integer.valueOf(100).equals(Long.valueOf(100))) {
System.out.println("second trial was true");
} else {
System.out.println("second trial was false");
}
if(100D == 100L) System.out.println("third trial, fun with doubles");
}
输出:
first trial happened
second trial was false
third trial, fun with doubles
这显然是正确的行为- Integer
是不是是 Long
.但是,是否存在 Number
子类的值等于",其返回值与 100 == 100L
返回true的方式相同?还是 100d == 100L
?换句话说,是否有一种方法(不是 Object.equals
)可以等效于对象的Binary Numeric Promotion行为?
This is obviously correct behavior - an Integer
is not a Long
. However, does there exist a "value equals" for Number
subclasses that would return true the same way that 100 == 100L
returns true? Or 100d == 100L
? In other words, is there a method (that is not Object.equals
) that will do the equivalent of the Binary Numeric Promotion behavior for objects?
推荐答案
Guava 提供了许多用于处理基元的实用工具,包括每种类型的compare()方法:
Guava provides several nice utilities for working with primitives, including a compare() method for each type:
int compare(prim a, prim b)
实际上,Java 7中已经向JDK添加了相同的功能.这些方法不提供任意的 Number
比较,但是它们为您提供了定义任何类型安全的粒度.通过选择要使用的类( Longs
, Doubles
等)进行比较.
And in fact, this same functionality has been added to the JDK as of Java 7. These methods don't provide arbitrary Number
comparisons, however they give you the granularity to define any type-safe comparison you'd like, by choosing which class (Longs
, Doubles
, etc.) to use.
@Test
public void valueEquals() {
// Your examples:
assertTrue(100 == 100l);
assertTrue(100d == 100l);
assertNotEquals(100, 100l); // assertEquals autoboxes primitives
assertNotEquals(new Integer(100), new Long(100));
// Guava
assertTrue(Longs.compare(100, 100l) == 0);
assertTrue(Longs.compare(new Integer(100), new Long(100)) == 0);
assertTrue(Doubles.compare(100d, 100l) == 0);
// Illegal, expected compare(int, int)
//Ints.compare(10, 10l);
// JDK
assertTrue(Long.compare(100, 100l) == 0);
assertTrue(Long.compare(new Integer(100), new Long(100)) == 0);
assertTrue(Double.compare(100d, 100l) == 0);
// Illegal, expected compare(int, int)
//Integer.compare(10, 10l);
// Illegal, expected compareTo(Long) which cannot be autoboxed from int
//new Long(100).compareTo(100);
}
这篇关于是否存在数字“值等于"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!