user973758
user973758

Reputation: 727

Determine if two objects contain references to the same object

I want to determine if the fields within an object contain any pointer aliasing?

For example:

class A {
    A a1;
    A a2;
}

A z = new A();

A y = new A();
y.a1 = z;
y.a2 = z;

A x = new A();
x.a1 = y;
x.a2 = z;

// i.e. x has a reference to y and to z, and y has a reference to z

In this example I want to determine that object x contains pointer aliasing since x.a1.a1 == x.a2

The idea I have is to use reflection to iterate the reference fields of the object, and for each field, build a set of references by traversing through each field storing references as I go (i.e. flatten each reference into a set of references). I would then look at the intersection of these sets. Is this a good solution to my question?

Upvotes: 0

Views: 82

Answers (1)

fge
fge

Reputation: 121740

If I understand your need correctly, what you need here is an IdentityHashSet:

public static boolean hasLoops(final A a)
{
    if (a.a2 == null)
         return false;
    final Set<A> set = new IdentityHashSet<>();
    set.add(a.a2);
    A other = a.a1;
    while (other != null) {
        if (!set.add(other))
            return true;
        other = other.a1;
   }
   return false;
}

Since you want equality for the same references, an IdentityHashSet is what you want; although if you don't implement .equals() or .hashCode(), a "regular" HashSet can also do the trick.

Upvotes: 2

Related Questions