【发布时间】:2012-02-14 17:18:45
【问题描述】:
这篇文章是我之前在此处找到的帖子的延续
Object comparison for equality : JAVA
根据收到的建议,我创建了以下类并使用 Eclipse IDE 执行了 equals()、hashcode() 覆盖 ....everything。但是,当我使用存储这些对象的数组列表的 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");
}
我得到的结果是“失败”
【问题讨论】:
标签: java object comparison equals hashcode