重写方法public class Test { Test test; @Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((test == null) ? 0 : test.hashCode());
return result;
} @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Test other = (Test) obj;
if (test == null) {
if (other.test != null)
return false;
} else if (!test.equals(other.test))
return false;
return true;
}}问:
if (obj == null)
return false;这个有什么用?如果test是null,obj也是null不就是true了吗?(只是假设,这个时候用equals会异常)           Test other = (Test) obj;
if (test == null) {
if (other.test != null)
return false;
} else if (!test.equals(other.test))
return false;这段...我不知道它是在比较什么...各位见笑了,求逐行讲解.另外重写hashcode的代码根本就看不懂.....

解决方案 »

  1.   


    //当obj不为空,且obj和test不是同一个对象时Test other = (Test) obj;//将obj转化为Test类型的对象other
            if (test == null) {
                if (other.test != null)
                    return false;//test为空,other不为空,不是同一个对象,返回false
            } else if (!test.equals(other.test))/**test, other均不为空,比较test对象和other对象的test字段,此时other.test是一个嵌套的实例
                return false;lz是否满意在下的解释啊,呵呵。。
      

  2.   

    1. 如果没有 if (obj == null) return false;
       这样的调用: test.equals(null);
       会在这里:if (getClass() != obj.getClass())  产生异常。2. Test other = (Test) obj;
       这句cast是不安全的,不推荐。
       如果硬要用Object作为parameter,在这句cast前检查:
       if(!(obj instanceof Test)) return false;   这段代码说:
          假如我自己的成员 test(类型为Test) 是null,而要比较的对象的成员 test 不是null,则返回false,
          否则,调用我的成员 test 的 equals 方法,与对象 obj 的 test 成员作比较,假如返回了false,
          那么我这里也返回false。
          否则返回true。
       总之,这是一段莫名其妙的递归。
      

  3.   

    能够进入成员方法equals,那么肯定本身是存在的嘛.楼主也就不要想test为null了,要是为null就进不了equals方法了
      

  4.   

    NullPointerException的引起是因为一个为空的对象却执行了它不应该执行的操作
    在你的程序中,test已经是一个空的对象了
    却要这个空的对象去执行它的方法,当然会报空指针了
      

  5.   

    其实用这个就OK啦
    if(obj instanceof Test){
           Test test = (Test)obj;
    }
      

  6.   


    这是Eclipse自动生成的覆盖了hashcode和equals方法的代码,是没有任何错误的,但是我看不懂
      

  7.   

    一般情况下不用覆盖这两个方法,我目前遇到的只有在用自己的类做map的key的时候要覆盖这两个方法。
      

  8.   


    1、Test other = (Test) obj;这里为什么要强制转换?前面已经做了if (getClass() != obj.getClass())的判断,如果能到这里,说明obj已经是Test类型了吧?  
    2、问题1中,强制转换之后,一定能保证obj里面也有test属性吗?因为下面用到了(other.test)做判断
    3、else if (!test.equals(other.test)),这里调用的equals方法的是谁的?String类的?还是??我现在糊涂了加分了,谢谢
      

  9.   

    1,if (getClass() != obj.getClass())之后虽然说明了obj是Test类型,但用obj这个引用只能访问Object类拥有的方法和属性,不能访问Test有而Object没有的属性和方法。
    2.因为前面的if已经做过判断了,所以强转是可以保证正常执行的。
    3.test的啊,test是String,所以调用的是String类的equals.
      

  10.   

    equals的还没明白呢?
    hashcode的那个谁能给我讲讲呀,。?
      

  11.   

    hashcode就是要给你的那个对象分配一个和别的对象都不一样的值,所以要把它写的尽量离散,就像下面那句写的
     result = prime * result + ((test == null) ? 0 : test.hashCode());
      

  12.   

    去看看effects java 里面关于euqels,hashcode的那2张,你会明白点吧