简体   繁体   English

从具有不连续索引的列表创建子列表

[英]Create sublist from list with non continuous indices

In Java, I would like to use the clear() method on a list so that the items cleared from the sublist are also removed from the original list. 在Java中,我想在列表上使用clear()方法,以便将从子列表中清除的项目也从原始列表中删除。 Is there a way to create a sublist where the indices are non continuous, so that I can still use the clear() method to remove the items from the original list? 有没有一种方法可以创建索引不连续的子列表,以便我仍然可以使用clear()方法从原始列表中删除项目?

Nope. 不。 Calling clear() on the sublist removes the elements from the original list, but also updates indices. 在子列表上调用clear()会从原始列表中删除元素,但也会更新索引。

If you want to retain the indices, instead of using .clear() you can use .set(i, null) - this will retain "empty slots" in the list. 如果要保留索引,则可以使用.set(i, null)代替使用.clear() .set(i, null) -这将在列表中保留“空槽”。 You'll just need to be careful when iterating. 迭代时只需要小心。 Another thing you can do is use a Map<Integer, Foo> where Integer is your index. 您可以做的另一件事是使用Map<Integer, Foo> ,其中Integer是您的索引。 That way you will be in charge of managing the indices. 这样,您将负责管理索引。

Update: if you want to remove particular elements, rather than a sublist, simply call .remove(index) 更新:如果要删除特定元素而不是子列表,只需调用.remove(index)

None of the default List implementations support this behavior. 默认的List实现均不支持此行为。 You could override ArrayList and support a clear() , remove() , etc.. that turns around and calls remove() on the parent list. 您可以重写ArrayList并支持clear()remove()等。它可以转过来并在父列表上调用remove()

Something like the following example code. 类似于以下示例代码。 But to keep it properly in sync with the parent is going to take a lot of work . 但是要与父母保持正确的同步需要大量的工作 If you can limit the number of calls that you need to support then it would be a lot easier of course. 如果您可以限制需要支持的电话数量,那么这当然会容易得多。

public class SubArrayList<T> extends ArrayList<T> {
    public SubArrayList(List<T> parentList, int start, int end) {
        ...;
    }

    @Override
    public T remove(int index) {
        T removed = super.remove(index);
        // should not remove by position because position in parent might change
        parentList.remove(removed);
        return removed;
    }

    @Override
    public T remove(Object obj) {
        if (super.remove(obj)) {
            parentList.remove(obj);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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