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

     

  • 相关阅读:
    什么是知行动手实验室?
    SpringBoot Admin2.0 集成 Java 诊断神器 Arthas 实践
    一文读懂容器存储接口 CSI
    AI 事件驱动场景 Serverless 实践
    一不小心,它成为了 GitHub Alibaba Group 下 Star 最多的开源项目
    5G 和云原生时代的技术下半场,视频化是最大最新的确定性
    基于 RocketMQ Prometheus Exporter 打造定制化 DevOps 平台
    Knative 基于流量的灰度发布和自动弹性实践
    阿里的 RocketMQ 如何让双十一峰值之下 0 故障?
    阿里巴巴开源容器镜像加速技术
  • 原文地址:https://www.cnblogs.com/jiangxifanzhouyudu/p/6746520.html
Copyright © 2020-2023  润新知