例子:
public class E{
public static void main(String []args){
Integer n1=new Integer(11);
Integer n2=new Integer(11);
System.out.println(n1==n2);
System.out.println(n1!=n2);
}
}
//output:false;true
这是为什么呢,为什么超乎了大家的想象,两个值命名都是11,但是输出结果却正好相反。原因就是==和!=操作符比较的是对象的引用,而不是对象的值。
如果要比较两个对象的实际内容是不是相同就要运用equeals(),但是这个方法并不适用于基本类型,就像集合对象不适用于基本类型一样,基本类型比较内容时直接使用==和!=即可。
public class E{
public static void main(String []args){
Integer n1=new Integer(11);
Integer n2=new Integer(11);
System.out.println(n1.equals(n2));
}
}
//output:true
结果显示,正如我所说,然而加入我们创建自己的类
class A{
int i;
}
class B{
public static void main(String []args){
A a1=new A();
A a2=new A();
a1.i=a2.i=10;
System.out.println(a1.equals(a2));
}
}//output:false
为什么又是false呢,因为equals()的默认行为是比较引用,所以除非在即的新类中覆盖equals方法,这就是覆盖的重要性。
public class E{
public static void main(String []args){
Integer n1=new Integer(11);
Integer n2=new Integer(11);
System.out.println(n1==n2);
System.out.println(n1!=n2);
}
}
//output:false;true
这是为什么呢,为什么超乎了大家的想象,两个值命名都是11,但是输出结果却正好相反。原因就是==和!=操作符比较的是对象的引用,而不是对象的值。
如果要比较两个对象的实际内容是不是相同就要运用equeals(),但是这个方法并不适用于基本类型,就像集合对象不适用于基本类型一样,基本类型比较内容时直接使用==和!=即可。
public class E{
public static void main(String []args){
Integer n1=new Integer(11);
Integer n2=new Integer(11);
System.out.println(n1.equals(n2));
}
}
//output:true
结果显示,正如我所说,然而加入我们创建自己的类
class A{
int i;
}
class B{
public static void main(String []args){
A a1=new A();
A a2=new A();
a1.i=a2.i=10;
System.out.println(a1.equals(a2));
}
}//output:false
为什么又是false呢,因为equals()的默认行为是比较引用,所以除非在即的新类中覆盖equals方法,这就是覆盖的重要性。