克隆实现未通过 'equals' 测试,调试时所有 variables/fields 都相同
Clone implementation not passing 'equals' test, all variables/fields are the same when debugging
我正在做作业以通过一系列测试,我实现了自己的 equals 和 clone 函数,但无法弄清楚为什么克隆的对象与原始对象不相等。
我试过在 if 语句的布尔表达式中将 Object 转换为 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." );
class 学生实现 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
相等。
这里:
Student clone = (Student) super.clone();
clone.fullName = (Name) fullName.clone();
但是你的 class 说:
private Name fullName;
private String id;
您省略了 id
字段。因此,您应该 添加 复制该 id
字段,或者如果它不相关,请将其从您的 equals()
实施中删除!
我正在做作业以通过一系列测试,我实现了自己的 equals 和 clone 函数,但无法弄清楚为什么克隆的对象与原始对象不相等。
我试过在 if 语句的布尔表达式中将 Object 转换为 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." );
class 学生实现 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
相等。
这里:
Student clone = (Student) super.clone();
clone.fullName = (Name) fullName.clone();
但是你的 class 说:
private Name fullName;
private String id;
您省略了 id
字段。因此,您应该 添加 复制该 id
字段,或者如果它不相关,请将其从您的 equals()
实施中删除!