Skip to main content

java unbox

· 2 min read

背景

想比较两个数字的时候:Long的equal比较的值,而不是对象的地址

    public boolean equals(Object obj) {
if (obj instanceof Long) {
return this.value == (Long)obj;
} else {
return false;
}
}

为什么?

因为涉及到binary numeric promotion

jls 文档

相关文档

// "==" 操作符 的jls 文档

15.21.1 Numerical Equality Operators == and !=
If the operands of an equality operator are both of numeric type, or one is of
numeric type and the other is convertible (§5.1.8) to numeric type, binary numeric
promotion is performed on the operands (§5.6.2).
// Binary Numeric Promotion 文档

5.6.2 Binary Numeric Promotion
When an operator applies binary numeric promotion to a pair of operands, each
of which must denote a value that is convertible to a numeric type, the following
rules apply, in order:
1. If any operand is of a reference type, it is subjected to unboxing conversion
// == 会触发 Binary Numeric Promotion
Binary numeric promotion is performed on the operands of certain operators:
• The multiplicative operators *, /, and % (§15.17)
• The addition and subtraction operators for numeric types + and - (§15.18.2)
• The numerical comparison operators <, <=, >, and >= (§15.20.1)
• The numerical equality operators == and != (§15.21.1)

所以

    @Test
public void testEq(){
Long i = new Long(1000L);
Long j = new Long(1000L);
Assert.assertFalse(i == j); // 两个都是对象 , 不满足Binary Numeric Promotion 条件 ,所以不会拆箱 , 所以比较的是地址

Assert.assertTrue(i == 1000L); // 这里 满足 Binary Numeric Promotion 条件 , 所以比较的是值
}