public class EqualsMethod {
public static void main(String[] args) {
Integer n1 = new Integer(47);
Integer n2 = new Integer(47);
System.out.println(n1.equals(n2));
}
}
Integer重写的Object的equals(),不是比较引用n1和n2的值的大小是否相等么?所以上面的返回的应该是TRUE.
为什么下面的程序是FAULSE了呢?
public class EqualsMethod {
public static void main(String[] args) {
Integer n1 = new Integer(47);
Integer n2 = new Integer(47);
System.out.println(n1.equals(47));
}
}
如题,谢谢....
public static void main(String[] args) {
Integer n1 = new Integer(47);
Integer n2 = new Integer(47);
System.out.println(n1.equals(n2));
}
}
Integer重写的Object的equals(),不是比较引用n1和n2的值的大小是否相等么?所以上面的返回的应该是TRUE.
为什么下面的程序是FAULSE了呢?
public class EqualsMethod {
public static void main(String[] args) {
Integer n1 = new Integer(47);
Integer n2 = new Integer(47);
System.out.println(n1.equals(47));
}
}
如题,谢谢....
47 在常量指中,不一样的,所以返回false
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}仅当参数不为空,并且为Integer对象,同时值相等时才为true
在JDK1.5版本包括JDK1.5版本中,答案是true,因为在JDK1.5加入了自动封箱机制,在
比较时,会把47包装成Integer。
还加入了自动解箱机制,你用47==n1 进行比较 答案也会是true。
java——类的包装器类型包装器有:Double,Float,Long,Integer,Short,Character和Boolean
J2SE将自动装箱/拆箱引入java中。
自动装箱的过程:每当需要一种类型的对象时,这种基本类型就自动地封装到与它相同类型的包装中。
自动拆箱的过程:每当需要一个值时,被装箱对象中的值就被自动地提取出来,没必要再去调用intValue()和doubleValue()方法。
自动装箱,只需将该值赋给一个类型包装器引用,java会自动创建一个对象。例如:
Integer i=100;//没有通过使用new来显示建立,java自动完成。
自动拆箱,只需将该对象值赋给一个基本类型即可。例如:int j=i;