Testing object equivalence

本文深入探讨了Java中使用==和!=操作符比较对象引用的问题,并介绍了如何使用equals()方法来比较对象的内容是否相等。此外,还通过实例说明了在自定义类中正确实现equals()方法的重要性。

The relational operators == and != also work with all objects,but their meaning often cunfuses the first-time java programmer.Here's an example:

public class Equivalence {

   public static void main (Sting[] args){

       Integer n1 = new Integer(47);

       Integer n2 = new Integer(47);

       System.out.println(n1 == n2);

       System.out.println(n1!=n2);

   }

}

/*output:false true*/

The statement System.out.println(n1 == n2) will print the result of the boolean comparosin within it.Surely the output shoule be "true" and then "false",since both Integer objects are the same. But while the contents of the objects are the same, the references are not the same .The operators == and !=  compare object regerences ,so the output is actually "false" and then "true".Naturally ,this surprises people at first.

What if you want to compare the actual contents of an object for equivalence? You must use the special method equals() that exists for all objects(not primitives,which work fine with == and !=).Here's how it's used:

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));

   }

}

/*output: true*/

The result is now what you expect.Ah,but it's not as simple as that;If you create your own class,like this:

class Value{

   int i ;

}

public class EqualsMethod2{

   public static void main(Sting[] args){

     Value v1 = new Value();

     Value v2 = new Value();

    v1.i = v2.i = 100;

   System.out.println(v1.equals(v2));

     }

}

/*output: false*/

 

things are confusing again: The result is false. This is because the default behavior of equals() is to compare references.So unless you override equals() in your new class you won't get the desired behavior.(Your new class does not override equals(),so the result is not the same as your expect!)

Most of the Java library classes implement equals() so that it compares the contents of objects instead of their references.

 

转载于:https://www.cnblogs.com/siyusiying/archive/2013/01/16/2862437.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值