Java 5新特性 for each 和Iterator的选择
在使用一边做迭代操作一边做删除数组元素操作是应该使用Iterator
package for_each_And_Iterator; public class Commodity { private String goods; private double price; private int num; public Commodity(String goods, double price, int num) { this.goods = goods; this.price = price; this.num = num; } public String getGoods() { return goods; } public double getPrice() { return price; } public int getNum() { return num; } public String toString() { return "Commodity [goods=" + goods + ", price=" + price + ", num=" + num + "]"; } }
package for_each_And_Iterator; import java.util.ArrayList; import java.util.List; public class For_eachDemo { public static double sum() { //创建三个商品对象 Commodity cy1 = new Commodity("phone", 1000.0, 5); Commodity cy2 = new Commodity("computer", 3000.0, 12); Commodity cy3 = new Commodity("headset", 15.0, 30); List<Commodity> list = new ArrayList<Commodity>(); list.add(cy1); list.add(cy2); list.add(cy3); double coy = 0.0; for (Commodity index : list) { // if(index.getPrice()<1000){ // //并发修改异常 // list.remove(index);//Exception in thread "main" java.util.ConcurrentModificationException // System.out.println(list); // } coy += (index.getPrice() * index.getNum()); } return coy; } public static void main(String[] args) { System.out.println(sum()); } }
package for_each_And_Iterator; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class IteratorDemo {
//获取商品单价小于1000的商品 public static double sum() { //创建三个商品对象 Commodity cy1 = new Commodity("phone", 1000.0, 5); Commodity cy2 = new Commodity("computer", 3000.0, 12); Commodity cy3 = new Commodity("headset", 15.0, 30); List<Commodity> list = new ArrayList<Commodity>(); list.add(cy1); list.add(cy2); list.add(cy3); double coy = 0.0; for (Iterator<Commodity> it = list.iterator(); it.hasNext();) { Commodity comy = it.next(); if (comy.getPrice() < 1000) { it.remove();//Iterator的.remove(); } } for (Commodity commodity : list) { coy += commodity.getPrice() * commodity.getNum(); System.out.println(commodity); } return coy; } public static void main(String[] args) { System.out.println(sum()); } }