从Java中的数组中删除负数
以下程序显示了如何从数组中删除负数。
示例
import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class Tester { public static void main(String[] args) { List<Integer> objArray = new ArrayList<Integer>(); objArray.clear(); objArray.add(2); objArray.add(-3); objArray.add(4); System.out.println("Array before removing an element "+objArray); Iterator<Integer> iterator = objArray.iterator(); while(iterator.hasNext()) { Integer next = iterator.next(); if(next < 0) { iterator.remove(); } } System.out.println("Array after removing an element"+objArray); } }
输出结果
Array before removing an element [ 2, -3, 4 ] Array after removing an element [ 2, 4 ]