Iterator迭代器的使用

本文通过具体实例演示了如何使用Java的集合类和迭代器进行数据操作,包括求总分、平均分、最高分和最低分的过程。通过定义学生类,创建学生对象集合,并运用迭代器遍历集合,实现数据的统计分析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
/**

  • Iterator迭代器:遍历集合,获取该集合的迭代器完成迭代操作。

  • 格式:Iterator<> 变量名=集合.iterator();

  • Iteratro的常用方法:

  • hasNext()方法:若集合仍有元素可以迭代,返回true.。

  • next()方法:返回迭代的下一个元素。

  • */
    public class HomeWorkDay02_05 {

    public static void main(String[] args) {

     Student stu01=new Student("张三",20,82);
     Student stu02=new Student("李四",21,89);
     Student stu03=new Student("王五",22,90);
     Student stu04=new Student("赵六",23,91);
     Student stu05=new Student("钱七",24,99);
     Collection<Student> coll=new ArrayList<>();
     coll.add(stu01);
     coll.add(stu02);
     coll.add(stu03);
     coll.add(stu04);
     coll.add(stu05);
    
     Iterator<Student> it=coll.iterator();
    
     //定义总分
     double totallScore=0;
     //定义最高分
     double maxScore=((ArrayList<Student>) coll).get(0).getScore();
     double mimScore=((ArrayList<Student>) coll).get(0).getScore();
    
     while(it.hasNext())
     {
    
        Student stu=it.next();
        totallScore+=stu.getScore();
    
        if(maxScore<stu.getScore())
    
            maxScore=stu.getScore();
        else if(mimScore>stu.getScore())
            mimScore=stu.getScore();
    
    
    
     }
     double avgScore=totallScore/coll.size();
    
     System.out.println("总分:"+totallScore+"最高分:"+maxScore+"最低分:"+mimScore);
    

    }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值