2013-10-12 112 views
2

此方法应接受列表,元素,最小值(含)和最大值(不含)。然后使用相同的元素删除范围内的所有元素。删除范围列表中的元素

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

我在接近列表的末尾时遇到了麻烦,它在其中删除了太多内容。有什么建议么?

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++; 
     } 
    } 
} 
+0

您可能需要使用一个迭代器。 –

回答

2

你能做到这样

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