Fis*_*hyK -2 java list arraylist
好吧,我有一个整数 ArrayList,我想从中删除奇数或大于 100 的条目。但是,我的代码不起作用,我真的不明白为什么?
list.add(1);
list.add(899);
list.add(5);
list.add(647);
list.add(4);
list.add(804);
list.add(103);
ArrayList<Integer> list2 = removeEntries(list);
public static ArrayList<Integer> removeEntries(ArrayList<Integer> list1) {
for(int i = 0; i < list1.size(); i++) {
while(list1.get(i) % 2 != 0 || list1.get(i) > 100) {
if(i != list1.size()) list1.remove(i);
}
}
return list1;
}
Run Code Online (Sandbox Code Playgroud)
这没有给我正确的 list2 条目,但我不明白为什么......
小智 5
List#removeIf使用Collection#removeIf继承自 的方法List。通过 aPredicate并注明您的删除标准。
像这样:
list.removeIf(x -> x != null && (x % 2 == 1 || x > 100));
System.out.println(list); // [4]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
59 次 |
| 最近记录: |