2015-03-19 45 views
3

您好我想重写我的自定义类的equal和hashcode方法。覆盖Java中的平等和散列码,其中this.obj为空

这里是我的自定义类

public class property 
{ 
    public String type = null; 
    public int value; 
    public int id; 
    public String name = null; 
    public String course = null; 



    public property(String type, String course, int value, int id) 
    { 
     this.value = value; 
     this.type = type; 
     this.course = course; 
     this.id = id; 
    } 

    @Override 
    public boolean equals(Object obj) { 
     if(this == obj) 
      return true; 
     if((obj == null) || (obj.getClass() != this.getClass())) 
      return false; 

     property sig = (property) obj; 

     if(sig != null) { 
      if(sig.type.equals("EST1")) { 
       if (sig.name != null && sig.type != null && sig.course != null) { 
        Log.d("property", "Other " + sig.course + "AHHAHAHA " + course + "shahahaaha " + sig.id + "babababaab " + id); 
        if (sig.course.equals(this.course) && sig.value == this.value && sig.type.equals(this.type) && sig.id == (this.id)) { 
         Log.d("property", "EST1"); 
         return true; 
        } 

      } 

     } 
     return false; 
} 

的问题是,“this.id,this.type”始终是空或0,我不明白为什么......而sig.id,sig.type有价值。只是为了让你知道它只是代码片段,而不是完整的代码,所以它可能有错别字,并且在逻辑上不正确。

+1

'this.id'不能为空,它可以是** 0 ** – 2015-03-19 11:01:24

+0

是像我说的可能会有错别字......对不起 – user3290805 2015-03-19 11:05:06

+1

你可以发布你实际调用'equals'方法的代码! – 2015-03-19 11:06:15

回答

1

你的代码在我身边工作得很好,所以我猜你的测试程序有些不同(或复杂? )来自我的。

我尝试以下测试,

property p = new property("a","b", 100, 200); 
System.out.println("id:"+p.id); 
System.out.println("type:"+p.type); 
System.out.println(p.equals(p) +" should be true.."); 

而且我得到了,

id:200 
type:a 
true should be true..