[英]Determine if two objects contain references to the same object
我想確定對象中的字段是否包含任何指針別名?
例如:
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
在這個例子中,我想確定對象x包含指針別名,因為x.a1.a1 == x.a2
我的想法是使用反射來迭代對象的引用字段,並且對於每個字段,通過遍歷存儲引用的每個字段來構建一組引用(即將每個引用展平為一組引用)。 然后我會看看這些集合的交集。 這是我的問題的一個很好的解決方案嗎?
如果我理解你的需要,你需要的是一個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;
}
由於您希望相同引用具有相等性,因此IdentityHashSet
就是您想要的; 雖然如果你沒有實現.equals()
或.hashCode()
,“常規” HashSet
也可以做到這一點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.