You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何检查变量是否引用当前集合元素及PositionList移除问题解析

Hey there! Let's tackle your two questions clearly and directly:

问题1:如何检查一个变量是否引用了当前(this)集合中的元素?

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!).

问题2:为何无法从listA中移除b?

Let's walk through your code line by line to see exactly what's going wrong:

  1. List<Integer> listA = new PositionList<>(); – We create a new PositionList instance called listA.
  2. Position<Integer> a = listA.add(1); – a now points to the Position of the integer 1 inside listA.
  3. Position<Integer> b = listA.add(7); – At this point, b points to the Position of 7 inside listA—this Position's owner is listA.
  4. List<Integer> listB = new PositionList<>(); – We create a second PositionList called listB.
  5. b = listB.add(7); – Here's the critical mistake! We're reassigning the b variable to point to the new Position of 7 inside listB. The original reference to listA's 7 is completely lost now.
  6. listA.remove(b); – When we call this, listA checks if the passed Position belongs to it (using the logic from question 1). But the current b has owner set to listB, not listA. So listA rejects the operation—it can't remove a Position that 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:15:11