简体   繁体   中英

trouble when deleting sublist from list in java

I have a function in java like

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?

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. 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. 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; 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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