java中==和equal的区别

一、直接使用==

public class EqualsMethod {
    public static void main(String[] args) {
        Integer n1 = new Integer(23);
        Integer n2 = new Integer(23);
        System.out.println(n1 == n2);
    }
}
输出为:false

两个值相同,为啥会输出false呢?

尽管对象的内容相同,然而对象的引用却是不同的,而==和!=比较的是对象的引用,所以会输出false。

二、使用equals

如果想比较两个对象的实际内容是否相同,此时必须使用所有对象都适用的特殊方法equals(),但这个方法不适用于基本类型,基本类型直接使用==和!=即可。

public class EqualsMethod {
    public static void main(String[] args) {
        Integer n1 = new Integer(23);
        Integer n2 = new Integer(23);
        System.out.println(n1.equals(n2));
    }
}
输出为:true

三、创建自己的类

如果自己创建一个类呢

class Value{
    int i;
}

public class EqualsMethod {
    public static void main(String[] args) {
        Value v1 = new Value();
        Value v2 = new Value();
        v1.i = v2.i = 23;
        System.out.println(v1.equals(v2));
    }
}
输出为:false

结果又为false,这是由于equals()的默认是比较引用的,所以除非在自己的新类中覆盖equals()方法,否则会得到不是我们想要结果。

四、比较

equals()默认的比较引用,为什么第二种会得到正确的结果呢,是由于Integer这个类覆盖了equals()方法。下面是Integer类中equals()方法。

/**
 * Compares this object to the specified object.  The result is
 * {@code true} if and only if the argument is not
 * {@code null} and is an {@code Integer} object that
 * contains the same {@code int} value as this object.
 *
 * @param   obj   the object to compare with.
 * @return  {@code true} if the objects are the same;
 *          {@code false} otherwise.
 */
 public boolean equals(Object obj) {
     if (obj instanceof Integer) {
         return value == ((Integer)obj).intValue();
     }
     return false;
 }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值