这篇文章是我以前的帖子延续这里找到对象比较...第2部分
Object comparison for equality : JAVA
根据我收到的建议,我创建了下面的类,做了equals()方法, hashcode()覆盖....使用Eclipse IDE的一切。但是,当我比较两个不同的对象时,我仍然得到一个错误,它们使用存储这些对象的ArrayList的contains()方法引用相同的类。我不知道我的实施过程中出了什么问题。想帮助排除故障。
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");
}
我得到的结果为“失败”
对不起,,,我已经更新了我的代码。两个对象属性都有相同的值..但我得到失败...... – Raghu 2012-02-14 17:34:42
我现在看到的唯一的东西就是缺少的“)”,我希望你的代码中有正确的东西吗? 如果(a1.contains(clsA2)<< == { 的System.out.println( “成功”);} 其他 { 的System.out.println( “失败”);} 对不起 – tres2k 2012-02-14 17:40:52
乡亲......这是我的错,我从一张表中得到了我不应该使用的数据,这给了我没有预料到的结果,因此也提出了这个问题,上面的代码工作得很好。帮助。 – Raghu 2012-02-14 20:51:19