When cloning an object, you must create a new object and not return the current object.
package com.codegym.task.task21.task2107;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
/*
Deep cloning of a map
*/
public class Solution implements Cloneable{
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Solution solution = (Solution) o;
return users.equals(solution.users);
}
@Override
public int hashCode() {
return Objects.hash(users);
}
public static void main(String[] args) throws CloneNotSupportedException {
Solution solution = new Solution();
solution.users.put("Hubert", new User(172, "Hubert"));
solution.users.put("Zapp", new User(41, "Zapp"));
// clone = null;
try {
Solution clone = (Solution)solution.clone();
System.out.println(solution);
System.out.println(clone);
System.out.println(solution.users);
System.out.println(clone.users);
} catch (CloneNotSupportedException e) {
e.printStackTrace(System.err);
}
}
protected Map<String, User> users = new LinkedHashMap();
public Solution clone()throws CloneNotSupportedException{
Solution s = new Solution();
User u1 = (User)this.users.get("Hubert").clone();
User u2 = (User)this.users.get("Zapp").clone();
s.users.put("Hubert",u1);
s.users.put("Zapp", u2);
return s;
}
public static class User implements Cloneable{
int age;
String name;
public User(int age, String name) {
this.age = age;
this.name = name;
}
public User clone()throws CloneNotSupportedException{
return (User)super.clone();
}
}
}