zoukankan      html  css  js  c++  java
  • 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()); } }

     

  • 相关阅读:
    LinkedBlockingQueue
    PriorityBlockingQueue
    js阻止事件冒泡
    java map常用的4种遍历方法
    JAVA jar 和 war 包的区别
    jquery 操作大全
    Java 使用new Thread和线程池的区别
    原生XMLHttpRequest
    socket 和 webscoket 的区别
    GET和POST请求的区别如下
  • 原文地址:https://www.cnblogs.com/jiangxifanzhouyudu/p/6746520.html
Copyright © 2011-2022 走看看