gpt4 book ai didi

java - JAVA 中的对象比较...第 2 部分

转载 作者:行者123 更新时间:2023-12-01 17:32:55 24 4
gpt4 key购买 nike

这篇文章是我在此处找到的上一篇文章的延续

Object comparison for equality : JAVA

根据我收到的建议,我创建了以下类并使用 Eclipse IDE 覆盖了 equals()、hashcode() ......一切。但是,当我使用存储这些对象的数组列表的 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");
}

我得到的结果是“失败”

最佳答案

我在 Netbeans 中测试了您的代码,结果成功。有一个错字,缺少“)”if(a1.contains(clsA2)

“当然失败了。您的测试代码中的 id 字符串为 null,并且如果发生这种情况,则 equals 方法被编写为返回 false。如果firstId 和 secondaryId 都为 null,或者其中一个为 null,也许您应该允许相等和另外两个匹配。”实在是不太对劲。

如果两个 id 都为 null,则 equals 将返回 true。仅当一个 ID 不存在时。

关于java - JAVA 中的对象比较...第 2 部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9281263/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com