简体   繁体   English

从列表中删除元素

[英]removing element from list

I have 2 lists, and depending on a parameter I remove an element from 1 of the 2 lists. 我有2个列表,并根据参数从2个列表中的1个删除元素。 I then loop through the lists for additional processing. 然后,我遍历列表进行其他处理。 However even though the list has lost 1 element, the list.size() is still the same causing a java.lang.IndexOutOfBoundsException . 但是,即使列表丢失了1个元素, list.size()仍然相同,从而导致java.lang.IndexOutOfBoundsException Is there anything I can do to fix this? 有什么我可以解决的吗?

    System.out.println(high_list_price.size());

    if(first_hit.equals("low")){
        high_list_date.remove(high_list_date.size()-1);
        high_list_price.remove(0);
        high_list_percent.remove(0);
    }
    if(first_hit.equals("high")){

        low_list_date.remove(low_list_date.size()-1);
        low_list_price.remove(0);
        low_list_percent.remove(0);
    }

    System.out.println(high_list_price.size());

    for(int tt = 0;tt < low_list_date.size();tt++){
        System.out.println(low_list_date.get(tt)+"|"+low_list_price.get(tt));
    }

    for(int ii = 0; ii < high_list_date.size();ii++){
        System.out.print(high_list_date.get(ii)+"|");
        System.out.println(+high_list_price.get(ii));
    }

high_list_price.size() = 51 both before and after the .remove, yet high_list_date.size() goes from 51 to 50, why is that? high.list_price.size()= .remove前后的51,但是high_list_date.size()从51变为50,为什么?

If you iterate through ArrayLists backwards, you can delete the current element without worrying about what comes after. 如果您向后遍历ArrayLists,则可以删除当前元素,而不必担心后续操作。
Another option is to iterate through, make a list of things to delete, then delete those elements form the original list. 另一个选择是遍历,创建要删除的事物的列表,然后从原始列表中删除那些元素。

As an addition to the valid options provided by @z5h there, consider using the Iterator interface, which includes a remove() method that removes the item from the underlying collection without causing the kinds of problems that using Collection.remove() causes. 除了@ z5h提供的有效选项之外,请考虑使用Iterator接口,该接口包括remove()方法,该方法从基础集合中删除项目,而不会引起使用Collection.remove()引起的各种问题。

Using Iterator might help you walk through your collections in a more readable fashion, as well. 使用Iterator可能也会帮助您以更具可读性的方式遍历集合。

you may want to use an ArrayList instead of an plain array. 您可能要使用ArrayList而不是普通数组。 It provides additional functions like remove(Object o) 它提供了其他功能,例如remove(Object o)

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

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