我需要编写一个在最小和最大范围之间过滤ArrayList的方法。因此,该方法接受List,int min和最大整数。 这是我写的方法。
public static List<Integer> filterRange(final List<Integer> l3,int min,int max)
{
System.out.println(l3);
Iterator<Integer> iter = l3.iterator();
while (iter.hasNext()) {
int i=iter.next();
if (i<=max && i>=min) {
iter.remove();
}
}
System.out.println(l3);
return l3;
}
然而,这不会起到所需的作用。对此的建议会很好。
由于
答案 0 :(得分:1)
您需要获取每个元素然后进行测试。目前,您连续两次致电next()
。因此,如果您有一个包含(1,2,3,4)的List并且您正在开始第一次迭代,那么这一行:
if (iter.next().intValue()<=6 && iter.next().intValue()>=2)
相当于:
if (1<=6 && 2>=2)
要避免存储该元素,然后执行测试。
while (iter.hasNext()) {
Integer i = iter.next();
if (i.intValue()<=6 && i.intValue()>=2) {
iter.remove();
}
}
请注意,您没有使用min
和max
参数值。另外,我不知道为什么你的方法是通用的。
<小时/> 编辑后,远离原始帖子,问题是您在不知道列表是否包含某些元素的情况下调用
next()
,即使它已经存在,也会无限循环,因为您没有调用{{ 1}}在你的循环中(因为next()
将始终返回hasNext()
)。所以它应该是:
true
请注意,您的列表可以包含 while (iter.hasNext()) {
int i=iter.next();
if (i<=6 && i>=2) {
iter.remove();
}
}
元素,因此当尝试取消null
对象中的值时,此行int i=iter.next();
可能会抛出NPE。
最后,如果你正在使用java-8(再次注意Integer
元素),你可以这样做:
null
答案 1 :(得分:1)
这里是filterRange函数的更通用版本。这需要作为参数:
List<T>
其中<T extends Comparable<T>>
它返回相同的列表,但删除了最小/最大范围之外的任何对象。
该函数遍历T列表,并使用Comparable接口方法compareTo()
将列表中的每个T与高值和低值进行比较。如果项目在范围内,则将项目添加到新列表中。
public static <T extends Comparable<T>> List<T> filterRange(List<T> list, T low, T high){
List<T> newlist = new ArrayList<T>();
for(T t:list) {
if(t.compareTo(low)>=0 && t.compareTo(high)<=0) {
newlist.add(t);
}
}
return list;
}
我用这段代码测试了它
String[] array = new String[]{"apple", "banana", "cherry",
"grape", "kiwi", "lemon",
"lime", "orange", "pear",
"plum", "strawberry"};
List<String> strings = Arrays.asList(array);
List<String> array1 = filterRange(strings,"c","h");
得到了:
cherry
grape
答案 2 :(得分:0)
你不能两次使用next()
功能。它每次都获得下一个元素。尝试将next()
的回复存储在本地变量中,然后再与min / max
进行比较。