2012-12-27 64 views
1

比較我有同一個實體「社區」兩個對象在Java中

和兩個對象(社區和COM)具有相同的價值觀

Communty.java有以下變量的兩個不同的對象:

private Integer communityId; 
    private String communityName; 
    private String description; 

    // many to many relationship 
    private Set<Faculty> faculties = new HashSet<Faculty>(); 
    private Set<User> users = new HashSet<User>(); 

我用相等的方法:

@Override 
    public boolean equals(Object obj) { 
      // TODO Auto-generated method stub 
      if(obj==null) 
       return false; 
      if(obj==this) 
       return true; 
      if(!(obj instanceof Community)) return false; 

      Community community = (Community)obj; 
      return community.getCommunityId() == this.getCommunityId(); 
    } 

當我檢查community==com,它返回false ..爲什麼?我做了什麼錯誤?這兩個對象都從數據庫中檢索!

+0

粘貼您的完整代碼。 –

+0

[==運算符和equals()有什麼區別? (與哈希碼()???)](http://stackoverflow.com/questions/4505357/what-is-the-difference-between-operator-and-equals-with-hashcode) – McDowell

+0

是否你已經overrided公共int hashCode() – swamy

回答

8

==比較鏈接的對象。

您應該明確地致電community.equals(com)。還要照顧null檢查。

+0

在使用community.equals(com)和community.getCommunityId()和com.getCommunityId相同之後,它仍然表示爲false! – cobra

+0

你應該檢查我的答案爲可能的原因 – Rahul

+0

嘗試改變你的'equals'方法中的最後一個語句爲'return this.getCommunityId()。equals(community.getCommunityId());' 正如其他答案所述, '整數',不像'int's也需要'equals'方法進行正確的比較。 –

1

因爲他們不提及同一個對象。 ==用於檢查是否同時指向同一個對象。

==對象指代相同。

equals內容等同。

試試這個

return community.getCommunityId().equals(this.getCommunityId()); 
0

當我檢查社區== COM,返回false ..爲什麼

這意味着,這兩個參考文獻完全一樣。即對同一個對象。你的意圖是

boolean equal = community.equals(com); 

順便說一句你的if (obj == null)檢查是多餘的。

3

因爲您使用==而不是equals()來比較對象(ID)。 ==測試兩個變量是否引用同一個對象。 equals()測試兩個變量是否引用兩個功能相等的整數(即具有相同的int值)。

除了枚舉之外,使用==比較對象幾乎總是一個缺陷。

1

您的equals方法的問題是您正在使用對象的==運算符。這裏的CommunityId必須是同一對象,以返回true:

return community.getCommunityId() == this.getCommunityId(); 

應該

return community.getCommunityId().equals(this.getCommunityId()); 
2

==兩個引用可以指向不管比較兩個不同位置的對象內容的。

您應該使用community.equals(com)檢查平等」

而且,你的equals方法包括以下部分:

community.getCommunityId() == this.getCommunityId() 

communityIdInteger對象時,==運營商可以給出整數陰性結果值不在[-127,128]範圍內,因爲這是一個單獨的概念,您可以稍後再檢查它。

您需要使用equals()有作爲或比較。 intValue()

return community.getCommunityId().equals(this.getCommunityId()) 
0
在Java中

==操作符比較兩個對象的內存地址,你的情況COMM和社區必須存儲在兩個不同的內存兩個不同的對象地址

0

你比較兩個不同的對象communityId的。 是否有必要將communityId聲明爲Integer?因爲Integer是一個對象。 你爲什麼不簡單地用一個原始類型int聲明communityId; int communityId應該工作。