java - Determine if two objects contain references to the same object -


i want determine if fields within object contain pointer aliasing?

for example:

class {     a1;     a2; }  z = new a();  y = new a(); y.a1 = z; y.a2 = z;  x = new a(); x.a1 = y; x.a2 = z;  // i.e. x has reference y , z, , y has reference z 

in example want determine object x contains pointer aliasing since x.a1.a1 == x.a2

the idea have use reflection iterate reference fields of object, , each field, build set of references traversing through each field storing references go (i.e. flatten each reference set of references). @ intersection of these sets. solution question?

if understand need correctly, need here identityhashset:

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

since want equality same references, identityhashset want; although if don't implement .equals() or .hashcode(), "regular" hashset can trick.


Comments

Popular posts from this blog

php - SPIP: From Tag directly to an article -

jquery - isAjaxRequest always return false -

ruby on rails - In a controller spec, how to find a specific tag in the generated view? -