简体   繁体   中英

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 (ie 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM