删除具有范围的列表中的元素 [英] Removing elements in a List withing a range

查看:65
本文介绍了删除具有范围的列表中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该方法应该接受列表,元素,最小值(含)和最大值(不含).然后,它将删除具有相同元素的范围内的所有元素.

This method is supposed to accept a list, a element, a min value(inclusive), and a max value(exclusive). It then removes all elements within the range with the same element.

例如,对于列表(0、0、2、0、4、0、6、0、8、0、10、0、12、0、14、0、16),调用removeInRange( list,0、5、13)应生成列表(0、0、2、0、4、6、8、10、12、0、14、0、16).

For example, for the list (0, 0, 2, 0, 4, 0, 6, 0, 8, 0, 10, 0, 12, 0, 14, 0, 16), a call of removeInRange(list, 0, 5, 13) should produce the list (0, 0, 2, 0, 4, 6, 8, 10, 12, 0, 14, 0, 16).

在列表末尾删除过多内容时,我遇到了麻烦.有什么建议吗?

I am having trouble with near the end of the list in which it removes too much. Any suggestions?

private static void removeInRange(List<Integer> thing, int element,
            int firstInclusive, int secondExclusive) {

    int i = firstInclusive;

    while ( i >= firstInclusive && i < secondExclusive && i < thing.size()) {
        if (thing.get(i)== element) {
            thing.remove(i);
        } else {
            i++;
        }
    }
}

推荐答案

您可以这样做

list.subList(fromIndex, toIndex).removeAll(Arrays.asList(element));

这篇关于删除具有范围的列表中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆