关于thinking in java中equals()方法的问题?

J2EE 码拜 9年前 (2015-05-11) 688次浏览 0个评论
 

我在看thinking in java 中有这么一个例子

例1
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));
  }
}
这个输出结果为true;
——————————————

例2
Class Value{
  int i;
}

Public Class EqualsMethod2{
  public Static void main(String[] args){
     Value v1 = new Value();
     Value v2 = new Value();
 System.out.println(v1.equals(v2)); 
  }  
}
而这个类的输出结果为false,因为equals()的缺省行为是拿references(指向堆中对象的指针)来比较的

但我看到这里就有个疑问,Integer 是个基本型别,但n1也是通过 new 关键字来产生,就是一个对象了,怎么例1中打印出的是true而不是false呢?是不是n1和n2中的值不是references了呢?有谁能指点以下吗?

5分
请问你这个Value是什么类型,自己新建的类型最好自己实现equals方法。
不然他将使用Object的equals方法,而这个方法在DOC中是这样说的:
The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true). 

Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes. 

建议阅读《effective Java》

15分
Integer类override了equals()方法,使得当两个Integer类所代表的值相等时equals()就返回true。
而你的Value类没有override方法equals(),那么Value类的equals()方法就继承了Object类的equals()的行为,就是比较两个两个对象的内存地址。所以就会有上面的结果。
如果你在Value类中也override equals()方法,那么也可以得到v1.equals(v2)的值为true。

Class Value{
  int i;
  public boolean equals(Object o){
      if(o instanceof Value){
          return this.i == o.i;
      }else{
          return false;
      }
  }    
}

5分
覆写equals方法就可以了,这样就可以按照你的意图来比较两个对象是否相同,不过最好同时覆写hashcode方法!
5分
因为Integer是int的wrapped class,它override了Object的equals()方法。
10分
因为Integer是int的wrapped class,它override了Object的equals()方
而你的Value类没有override方法equals(),那么Value类的equals()方法就继承了Object类的equals()的行为,就是比较两个两个对象的内存地址。所以就会有上面的结果。
======================================================
copy

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明关于thinking in java中equals()方法的问题?
喜欢 (0)
[1034331897@qq.com]
分享 (0)

文章评论已关闭!