简体   繁体   English

从java中的列表中删除子列表时出现问题

[英]trouble when deleting sublist from list in java

I have a function in java like 我在java中有一个函数

void remove(List<Var> vars, List<List<Value>> vals) {
    int index = calculateIndex();
    vars.removeAll(vars.subList(index, vars.size()));
    vals.removeAll(vals.subList(index, vals.size()));

} }

always both lists have the same number of elements before enter the method, but, after removeAll vars have one element more than vals, index is between zero and the size of the lists, why could this be happening? 在输入方法之前,两个列表总是具有相同数量的元素,但是,在removeAll vars有一个元素而不是vals之后,index介于零和列表大小之间,为什么会发生这种情况呢?

If I understand correctly what you're trying to do, the code to remove the sublists should look like 如果我正确理解您要执行的操作,则删除子列表的代码应如下所示

int index = calculateIndex();
vars.subList(index, vars.size()).clear();
vals.subList(index, vals.size()).clear();

removeAll isn't the right tool for the job. removeAll不适合这项工作。 The purpose of removeAll is to look at all the elements in collection A, and remove elements in collection B that are equal to any element in collection A. I believe it uses .equals to determine which elements are equal, not reference equality, which means that you could be removing some elements you don't intend to remove. removeAll的目的是查看集合A中的所有元素,并删除集合B中与集合A中的任何元素相等的元素。我相信它使用.equals来确定哪些元素相等,而不是引用相等,这意味着你可以删除一些你不想删除的元素。 Furthermore, since the collection A in this case would be a sublist of collection B, so that they overlap, I wouldn't count on removeAll to function correctly anyway, although it might; 此外,由于在这种情况下集合A将是集合B的子列表,因此它们重叠,我不会指望removeAll无论如何都能正常运行,尽管它可能; using overlapping lists in this situation could lead to havoc. 在这种情况下使用重叠列表可能会导致严重破坏。

As an alternative design and not necessarily on track, I think it would be a nicer method if you actually constructed a new List containing the difference and returned it preserving both the original lists, otherwise its a slight code smell. 作为一种替代设计而不一定在轨道上,我认为如果你真的构造了一个包含差异的新List并且保留了两个原始列表,那么这将是一个更好的方法,否则它会有轻微的代码味道。

ie

List<Var> difference(List<Var> vars, List<List<Value>> vals) {
    List<Var> results = new ArrayList<Var>();

    // Loop through Vars and Vals appropriately adding Var to results based on some criteria
    //  ....

    return results;
}

This way you preserve List vars from appearing to magically change when passed in as a input parameter to a method. 这样,您可以保留List vars在作为输入参数传入方法时显得神奇地改变。

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

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