为什么我可以像原始一样测试Wrappers的不等式?我可以为我创建的课程吗? [重复]

问题描述 投票:2回答:1

这个问题在这里已有答案:

在Java中,存在仅包含单个基本类型的包装器对象。它们是Integer, Double, Character, Boolean, Byte, Short, Long, Float,分别包装了int, double, char, boolean, byte, short, long, float原始类型。

对于大多数对象,它们无法进行比较,但您可以实现ComparableComparator,以便您可以定义给定类型的一个对象(称为Ty)何时小于,等于或大于同一类型Ty的另一个对象。但是,如果是这样,你可以使用compareTo(Ty oth)compare(Ty arg0, Ty arg1)测试不等式,两者都返回int,表示小于if返回值<0,反之亦然。

但是,对于数字包装器对象(包括Character),您实际上可以使用基本<, <=, >=, >的不等式关系运算符来比较这些对象,如下面的代码所示:

Integer a = 15;
Integer b = 0;
Double x = 7.5;
Double y = 15.000000000000000000000000001; // Decimal part discarded
Character ch = 'A';

System.out.println(x + " < " + a + " is " + (x < a));
System.out.println(x + " < " + b + " is " + (x < b));
System.out.println(a + " > " + b + " is " + (a > b));

System.out.println(ch + " <= " + 65 + " is " + (ch <= 64)); // 'A' has ASCII code 65
System.out.println(ch + " <= " + 65 + " is " + (ch <= 65));
System.out.println(a + " >= " + b + " is " + (a >= b));

哪个输出

7.5 < 15 is true
7.5 < 0 is false
15 > 0 is true
A <= 65 is false
A <= 65 is true
15 >= 0 is true

请注意,在两个对象之间,==!=始终有效,并分别表示引用相等和不等式。这不是问题的一部分。

这些包装函数的“运算符重载”对于包装器是否是唯一的?

java integer wrapper unboxing
1个回答
2
投票

首先 - 揭示了一整个影响的老鼠。

发生的事情是,对于运算符'='','<=','<'和'>',编译器已经知道它们只能在基本类型上执行,因此会自动发生拆箱(转换对象)输入到基本类型)。这就是为什么这些运算符可以在Integer实例上执行的原因。

但是,当使用'=='或'!='时,编译器知道它可以直接比较实例,基本上比较两个变量是否引用相同的对象。它根本不是真正的整数比较。

事实上,这将返回错误:

System.out.println("Test == :"+(new Integer(1000) == new Integer(1000)));
System.out.println("Test == :"+(new Integer(100) == new Integer(100)));

这些很可能会返回false:

System.out.println("Test == :"+((Integer)1000 == (Integer)1000));
System.out.println("Test == :"+(Integer.valueOf(1000) == Integer.valueOf(1000)));

虽然这些最有可能会返回真实:

System.out.println("Test == :"+((Integer)100 == (Integer)100));
System.out.println("Test == :"+(Integer.valueOf(100) == Integer.valueOf(100)));

“最有可能”因为它将特定于实现,甚至可以通过参数控制。

由于使用Integer.valueOf(int)静态工厂方法时,值为-127..128的整数对象被实例化。见a more elaborate explenation

但请永远不要认为这将永远有效,并始终使用Comparable界面,.equals(...),或进行拆箱。

作为参考,还要查看这些文章:

© www.soinside.com 2019 - 2024. All rights reserved.