0

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.

3 Answers3

4

Assign to the same variable.

if (t1.equals(t2)) {
    System.out.println("iguais");
    t2 = t1;
}

It will assign t2 variable to the same memory address as t1. If the are no references to the old t2 object, it will get destroyed by garbage collector in the next collection cycle.

Vaidas
  • 1,494
  • 14
  • 21
  • Thank you. For me, it works because the reference pointer was created when t1 = t2. But I figured there was a way to do this in Java just by recognizing that two things are equal by equals. – Fabian Brandão Apr 06 '18 at 12:39
1

The answers above have answered your question. To follow on, you can look at how Strings are interned to save memory. More information can be found at: What is String interning?

  • Interesting this concept. But from what I saw, there is not a pool for Objects in general, just String due to usability. But the answer helps me to understand that the previous ones follow the same concept. Thank you very much. – Fabian Brandão Apr 06 '18 at 12:51
0

Just assign t1 the same object as t2. It would look something like this in code:

if (t1.equals(t2)) {
    t1 = t2;
}