gpt4 book ai didi

java - 克隆实现未通过 'equals' 测试,调试时所有变量/字段都相同

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

我正在做作业以通过一系列测试,我实现了自己的 equals 和 clone 函数,但无法弄清楚为什么克隆的对象不等于原始对象。

我尝试在 if 语句的 boolean 表达式中将对象强制转换为 Student,但这没有执行任何操作。

测试文件

Name n1 = new Name("John","Rockefeller");
Student s1 = new Student(n1, "123456");
Student s3 = s1.clone();
if ( s1.equals ( s3 ) )
System.out.println ( "\t\tSuccess - Students s1 and s3 are the same." );

Student 类实现 Cloneable

private Name fullName;
private String id;

@Override
public Student clone(){
try {
Student clone = (Student) super.clone();

clone.fullName = (Name) fullName.clone();
return clone;
} catch (CloneNotSupportedException e) {
System.out.println("Error: " + e);
return null;
}
}

public boolean equals ( Object obj ) {
if (this == (Student) obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Student calc = (Student) obj;

return Objects.equals(this.fullName, calc.fullName) && Objects.equals(this.id, calc.id);
}

预期:测试通过,但是在观察调试跟踪器中的变量后,我不知道为什么它没有通过。值相等。

最佳答案

您的clone方法不会复制id。您的 equals 方法期望 id 相等。

关于java - 克隆实现未通过 'equals' 测试,调试时所有变量/字段都相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57680114/

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