Console output is promising because I got "false" on equals two Solution objects, but "true" on hashcode.
I understand it that hashcode is the same because it was copied, and equals return "false" because I got two different objects now.
But why console result is:
SOLUTION : com.codegym.task.task21.task2107.Solution@e60d3e91
CLONE : com.codegym.task.task21.task2107.Solution@e60d3e91
SOLUTION.USERS : {Hubert=com.codegym.task.task21.task2107.Solution$User@372f7a8d, Zapp=com.codegym.task.task21.task2107.Solution$User@2f92e0f4}
CLONE.USERS : {Hubert=com.codegym.task.task21.task2107.Solution$User@372f7a8d, Zapp=com.codegym.task.task21.task2107.Solution$User@2f92e0f4}
Why numbers after "@" sign aren't different? I was thought that when I have two different object in different location memory, numbers are different.
package com.codegym.task.task21.task2107;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
/*
Deep cloning of a map
*/
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;
try {
clone = (Solution) solution.clone();
System.out.println("SOLUTION : " + solution);
System.out.println("CLONE : " + clone);
System.out.println("SOLUTION.USERS : " + solution.users);
System.out.println("CLONE.USERS : " + clone.users);
System.out.println(solution.equals(clone));
System.out.println(solution.users == clone.users);
} catch (CloneNotSupportedException e) {
e.printStackTrace(System.err);
}
}
@Override
public Object clone() throws CloneNotSupportedException {
Solution s = (Solution) super.clone();
s.users = new HashMap<>(users);
return s;
}
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
public Object clone() throws CloneNotSupportedException {
User u = (User) super.clone();
u.age = age;
u.name = name;
return u;
}
// @Override
// public String toString() {
// return "User{" +
// "age=" + age +
// ", name='" + name + '\'' +
// '}';
// }
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Solution solution = (Solution) o;
return Objects.equals(users, solution.users);
}
@Override
public int hashCode() {
return Objects.hash(users);
}
// @Override
// public String toString() {
// return "Solution{" +
// "users=" + users +
// '}';
// }
}