在 Java 中,存在仅包含单个基本类型的包装对象。他们是Integer, Double, Character, Boolean, Byte, Short, Long, Float
,将 int, double, char, boolean, byte, short, long, float
装箱分别为原始类型。
对于大多数对象,它们无法进行比较,但您可以实现 Comparable
或Comparator
因此,您可以定义给定类型的一个对象(称为 Ty
)何时小于、等于或大于相同类型的另一个对象 Ty
。但是,如果是这样,您可以使用 compareTo(Ty oth)
来测试不等式。或compare(Ty arg0, Ty arg1)
,都返回 int
,如果返回值 < 0 则表示小于,反之亦然。
但是,对于数字 Wrapper 对象(包括 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
请注意,在两个对象之间,==
和!=
始终有效,并且分别表示引用相等和不相等。这不是问题的一部分。
这些包装器函数的“运算符重载”是包装器所独有的吗?
最佳答案
首先 - 整个老鼠巢的含义已经被揭开。
发生的情况是,对于运算符“>=”、“<=”、“<”和“>”,编译器已经知道它们只能在基本类型上执行,因此会自动进行拆箱(将对象类型转换为原始类型)。这就是为什么这些运算符可以在 Integer 实例上执行。
但是,当使用“==”或“!=”时,编译器知道它可以直接比较实例,基本上是比较两个变量是否引用同一个对象。这根本不是真正的整数比较。
事实上,这将返回 false:
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)));
尽管这些很可能会返回 true:
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
接口(interface)、.equals(...)
,或进行拆箱。
作为引用,另请查看这些文章:
关于java - 为什么我可以像基元一样测试包装器的不平等?我可以为我创建的类(class)执行此操作吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50340496/