I have two objects that are the same according to the equals () method. Is there any way to get them to occupy the same memory address, so that there is only one object and several references? The goal is to optimize memory consumption. See the following code:
import java.util.Objects;
public class Test {
int x;
String y;
public static void main(String[] args) {
Test t1 = new Test();
t1.x = 1;
t1.y = "T1";
Test t2 = new Test();
t2.x = 1;
t2.y = "T1";
System.out.println(t1 + "\n" + t2);
if (t1.equals(t2)) {
System.out.println("iguais");
}
else {
System.out.println("diferentes");
}
t1.y = "Novo";
System.out.println(t1 + "\n" + t2);
if (t1.equals(t2)) {
System.out.println("iguais");
}
else {
System.out.println("diferentes");
}
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Test test = (Test) o;
return x == test.x && Objects.equals(y, test.y);
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
@Override
public String toString() {
return "Test{" + "x=" + x + ", y='" + y + '\'' + '}';
}
}
In this case, I would like to make t2 be the same as t1. Thank you.