Friday, 21 April 2017
java - Clone implementation not passing 'equals' test, all variables/fields are the same when debugging
Answer
Answer
I'm doing a homework assignment to pass a series of tests, I implemented my own equals and clone function, and can't figure out why the cloned object isn't equal to the original.
I've tried casting the Object to Student in the boolean expression of the if statement, but that hasn't done anything.
Testfile
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 Student implements 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);
}
Expected: The test passes, however after watching the variables in the debugging tracker I have no idea why it's not passing. The values are equal.
Answer
Your clone
method does not copy id
. Your equals
method expects the id
s to be equal.
Subscribe to:
Post Comments (Atom)
c++ - Does curly brackets matter for empty constructor?
Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...
-
A fair amount of the second act of The Dark Knight Rises has a class warfare plotline. This is foreshadowed in the trailers with Selina Ky...
-
How can I detect either numbers or letters in a string? I am aware you use the ASCII codes, but what functions take advantage of the...
-
I want to create an options array from a string. How can i create an array as { width : 100, height : 200 } from a string ...
No comments:
Post a Comment