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?

Answers


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.


Need Your Help

How to load a XML file on another domain than our [cross domain problem]

javascript xml cross-domain

I've got an XML file on my server, and my partners have to access it via a javascript I'm coding.

Executing commands over SSH using Java Spring

java spring ssh spring-boot

Me and a colleague are developing an web application to control a computer cluster. This computer cluster lacks an API so we need to be able use the Linux shell to control and add "jobs" via bash s...