if(new Integer(1) == new Integer(1)) return true;我需要对此进行编码/实现,以便此测试:
//door is a class and the constructor takes length, breadth, width
if(new Door(10,10,10) == new Door(10,10,10))将返回true。
Java编译器是否为包装器类提供了获取其值并对其进行比较的接口?
或者简单地说:如何检查some object > other object (用户定义的对象,而不是通过一些原始值/包装器类)?
发布于 2013-05-25 16:21:39
它在Java中不起作用:
if (new Integer(1) == new Integer(1)) {
System.out.println("This will not be printed.");
}您可能会混淆自动装箱,它将重用对象的小值(确切的范围是特定于实现的-请参阅JLS section 5.1.7的底部):
Integer x = 1;
Integer y = 1;
if (x == y) { // Still performing reference equality check
System.out.println("This will be printed");
}new运算符始终返回对新对象的引用,因此new ... == new ...的计算结果始终为false。
你不能在Java语言中重载运算符--通常对于相等比较,你应该使用equals (你可以在你自己的类中覆盖和重载它)并实现Comparable来排序,然后使用compareTo。
发布于 2013-05-25 16:27:51
==将比较“对象的引用”的值,而不是“对象的值”本身。
Here is the good reference,它将帮助你清楚java中比较是如何工作的,以及如何实现你所需要的东西。
https://stackoverflow.com/questions/16747745
复制相似问题