簡體   English   中英

比較Java中的兩個對象

[英]Comparing two objects in Java

我有兩個相同實體“社區”的不同對象

並且兩個對象(community和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 ..為什么? 我犯了什么錯誤? 這兩個對象都是從數據庫中檢索到的!

==比較到對象的鏈接。

您應該顯式調用community.equals(com) 還要注意檢查。

因為您正在使用==而不是equals()比較對象(ID equals() ==測試兩個變量是否引用同一對象。 equals()測試兩個變量是否引用兩個函數上相等的整數(即,具有相同的int值)。

除枚舉外,幾乎總是使用==比較對象的錯誤。

==比較可能指向兩個不同位置的兩個引用,而不管對象的內容如何。

您應該使用community.equals(com)檢查是否相等”

另外,您的equals方法包含以下段:

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

由於communityId是一個Integer對象,對於因interning而不在[-127,128]范圍內的整數值, ==運算符可能給出負數結果,那就是一個單獨的概念,您可以稍后進行檢查。

您還需要在其中使用equals()或比較。 intValue()

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

因為,它們沒有引用相同的對象。 ==用於檢查是否都引用相同的對象。

==對於對象是指相同的。

equals內容當量。

嘗試這個

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

equals方法的問題在於您對對象使用==運算符。 在這里,CommunityId必須是相同的對象才能返回true:

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

它應該是

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

當我檢查community == com時,它返回false ..為什么

這意味着; 這兩個引用完全相同嗎? 即到同一對象。 你原本打算

boolean equal = community.equals(com);

順便說一句,您的if (obj == null)檢查是多余的。

Java中的==運算符比較兩個對象的內存地址,在這種情況下,comm和community必須是兩個不同的對象,分別存儲在兩個不同的內存地址

您正在比較社區ID的兩個不同的對象。 有必要將communityId聲明為Integer嗎? 因為Integer是一個對象。 為什么不簡單地用原始類型int聲明communityId呢? int communityId應該工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM