==、!=和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方法,这就是覆盖的重要性。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值