如何检查变量是否引用当前集合元素及PositionList移除问题解析
Hey there! Let's tackle your two questions clearly and directly:
In most position-aware collection implementations (like your PositionList), each Position instance keeps a reference to the collection it belongs to—let's call this reference owner for example. To check if a given Position is part of the current (this) collection, you just need to compare the owner of the position to this.
For example, if your Position class has a field like this:
private List<E> owner;
Then the check method in your PositionList would look like:
public boolean isElementOfCurrentCollection(Position<E> pos) { return pos.owner == this; // Reference equality checks if it's the same collection instance }
This works because every time you add an element to the collection, you initialize the Position's owner to the collection itself. This prevents invalid cross-collection operations (which ties right into your second question!).
Let's walk through your code line by line to see exactly what's going wrong:
List<Integer> listA = new PositionList<>();– We create a newPositionListinstance called listA.Position<Integer> a = listA.add(1);–anow points to thePositionof the integer 1 inside listA.Position<Integer> b = listA.add(7);– At this point,bpoints to thePositionof 7 inside listA—thisPosition'sowneris listA.List<Integer> listB = new PositionList<>();– We create a secondPositionListcalled listB.b = listB.add(7);– Here's the critical mistake! We're reassigning thebvariable to point to the newPositionof 7 inside listB. The original reference to listA's 7 is completely lost now.listA.remove(b);– When we call this, listA checks if the passedPositionbelongs to it (using the logic from question 1). But the currentbhasownerset to listB, not listA. So listA rejects the operation—it can't remove aPositionthat doesn't belong to it.
If you wanted to remove the original 7 from listA, you shouldn't have overwritten the b variable. You'd need to keep that original reference intact, like this:
List<Integer> listA = new PositionList<>(); Position<Integer> a = listA.add(1); Position<Integer> bFromListA = listA.add(7); // Keep this reference List<Integer> listB = new PositionList<>(); Position<Integer> bFromListB = listB.add(7); // Use a different variable listA.remove(bFromListA); // Now this works!
内容的提问来源于stack exchange,提问作者Alex

