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()); } }

     

  • 相关阅读:
    20、职责链模式
    19、命令模式
    18、桥接模式
    17、单例模式
    javascript移动端实现企业图谱总结
    前端用js模拟疫情扩散开发总结
    移动端企业图谱开发兼容性等问题踩坑
    js实现企业图谱(pc端企业图谱项目总结与踩坑分享)
    基于vue脚手架的项目打包上线(发布)方法和误区
    实现一个网页版的聊天室(类似于钉钉群)
  • 原文地址:https://www.cnblogs.com/jiangxifanzhouyudu/p/6746520.html
Copyright © 2011-2022 走看看