この投稿は、私は次のクラスを作成したとequalsをした、ここでオブジェクト比較...パート2
私が受け取った提案に基づいて Object comparison for equality : JAVAを見つけた私の以前の記事の続きです()、 hashcode()はEclipse IDEを使用してすべてを上書きします。しかし、これらのオブジェクトが格納されているarraylistのcontains()メソッドを使用して、同じクラスを参照する2つの異なるオブジェクトを比較すると、私はまだfalseになります。私の実装で何が間違っているのか分かりません。トラブルシューティングをご希望ですか?
public class ClassA {
private String firstId;
private String secondId;
/**
* @return the firstId
*/
public String getFirstId() {
return firstId;
}
/**
* @param firstId the firstId to set
*/
public void setFirstId(String firstId) {
this.firstId = firstId;
}
/**
* @return the secondId
*/
public String getSecondId() {
return secondId;
}
/**
* @param secondId the secondId to set
*/
public void setSecondId(String secondId) {
this.secondId = secondId;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
public int hashCode() {
final int PRIME = 31;
int result = 1;
result = PRIME * result + ((firstId == null) ? 0 : firstId.hashCode());
result = PRIME * result + ((secondId == null) ? 0 : secondId.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final ClassA other = (ClassA) obj;
if (firstId == null) {
if (other.firstId != null)
return false;
} else if (!firstId.equals(other.firstId))
return false;
if (secondId == null) {
if (other.secondId != null)
return false;
} else if (!secondId.equals(other.secondId))
return false;
return true;
}
}
ClassA clsA1 = new ClassA();
ClassA clsA2 = new ClassA();
clsA1.setFirstId("value1");
clsA1.setSecondId("value2");
clsA2.setFirstId("value1");
clsA2.setSecondId("value2");
ArrayList a1 = new ArrayList();
ArrayList a2 = new ArrayList();
a1.add(clsA1);
a2.add(clsA2);
if(a1.contains(clsA2)
{
System.out.println("Success");
}
else
{
System.out.println("Failure");
}
a1
はあなたがa1
にclsA2
を追加していないclsA2
が含まれている場合はチェックしているので、あなたが「失敗」を取得している
申し訳ありません,,,私のコードを更新しました。両方のオブジェクトのプロパティは同じ値を持っています。しかし、私は失敗します.... – Raghu
あなたが今見ているものは、いなくなっています ")"、あなたのコードで正しいと思いますか? IF(a1.contains(clsA2)<< == { のSystem.out.println( "成功");} 他{ のSystem.out.println( "失敗");} – tres2k
申し訳人々それは私の予想していなかった結果であったため、この質問はうまくいきました。上記のコードはうまくいきます。手伝い。 – Raghu