Hello, I don't understand where is my error (The cloned object's users map should be equal (comparison using equals) to the users map of the cloned object.).
With my own tests everything seems alright regarding to the deep copy and the return value of the equals method.
Any help is welcome ^^
package com.codegym.task.task21.task2107;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
public class Solution implements Cloneable{
public static void main(String[] args) {
Solution solution = new Solution();
solution.users.put("Hubert", new User(172, "Hubert"));
solution.users.put("Zapp", new User(41, "Zapp"));
Solution clone = null;
try {
clone = (Solution) solution.clone();
System.out.println(solution);
System.out.println(clone);
System.out.println(solution.users);
System.out.println(clone.users);
//System.out.println(solution.equals(clone));
} catch (CloneNotSupportedException e) {
e.printStackTrace(System.err);
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Solution)) return false;
Solution solution = (Solution) o;
if(solution.users.size() != this.users.size()) return false;
if(!(this.users.keySet().equals(solution.users.keySet()))) return false;
String key;
Iterator<String> it = this.users.keySet().iterator();
while (it.hasNext()) {
key = it.next();
if(this.users.get(key).name == null && solution.users.get(key).name == null) continue;
if(this.users.get(key).name != null && solution.users.get(key).name == null ||
this.users.get(key).name == null && solution.users.get(key).name != null) return false;
if (!(this.users.get(key).name.equals(solution.users.get(key).name))) return false;
if (!(this.users.get(key).age == solution.users.get(key).age)) return false;
}
return true;
}
@Override
public int hashCode() {
return Objects.hash(users);
}
@Override
protected Object clone() throws CloneNotSupportedException {
Solution cloned = (Solution) super.clone();
Map<String, User> clonedMap = new LinkedHashMap<String, User>();
String key;
Iterator<String> it = this.users.keySet().iterator();
while (it.hasNext()) {
key = it.next();
clonedMap.put(key, (User) this.users.get(key).clone());
}
cloned.users = clonedMap;
return cloned;
}
protected Map<String, User> users = new LinkedHashMap<>();
public static class User implements Cloneable{
int age;
String name;
public User(int age, String name) {
this.age = age;
this.name = name;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
}