Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if an object is the same one or different

I know that this.toString() does not print the address of the object but the hash code. And I have read discussions like this one as well

But, lets say this.toString() prints the same value on 2 occasions and a different value on the 3rd occasion. Then, can I conclude that the object on the first 2 occasions was the same and the third occasion was different?

I am trying to determine(only for testing) if an object is the same one or a different one. Like say this points to same address or different.

Any better ways of checking if an object is the same or different one in Java running on Android devices? Or if I could get the address of the object in some way then the whole dilemma is resolved.

like image 764
AdeleGoldberg Avatar asked Jan 25 '23 17:01

AdeleGoldberg


1 Answers

There are three main ways to compare two objects in Java:

  1. Compare object references (the one you're looking for)

    obj1 == obj2
    

    This condition will be true if and only if both references are pointing to the same object.

    CustomType obj1 = new CustomType();
    CustomType obj2 = ob1;
    boolean thisIsTrue = obj1 == obj2;
    

    but:

    CustomType obj1 = new CustomType();
    CustomType obj2 = new CustomType();
    boolean thisIsFalse = obj1 == obj2;
    
  2. Compare object data

    obj1.equals(obj2)
    

    The result of this condition depends on actual implementation of equals method on obj1's class. E.g. this poorly designed equals method will always return false. Even if obj1 and obj2 are pointing to the same object.

    @Override
    public boolean equals(Object other){
        return false;
    }
    
    CustomType obj1 = new CustomType();
    CustomType obj2 = ob1;
    boolean thisIsTrue = obj1 == obj2;
    boolean thisIsFalse = obj1.equals(obj2);
    
  3. Compare object hash-codes

    obj1.hashCode() == obj2.hashCode()
    

    The result of this condition depends on actual implementation of hashCode method on both obj1's and obj2's classes. Using this approach is not encouraged as it is even less trustable. Two completely different objects can have the same hash-code. It should be used providently and cautiously in some specific cases.

like image 56
ETO Avatar answered Jan 30 '23 00:01

ETO