zoukankan      html  css  js  c++  java
  • JAVA集合中的迭代器的遍历

    JAVA中的迭代器,迭代实质上就是遍历,在JAVA中使用iterator()方法进行迭代。需要注意的是,iterator()方法的返回值是Iterator对象。Iterator对象有三个方法,hasNext(),next(),remove().

    代码:    public static void main(String[] args) {
            // TODO Auto-generated method stub
            Collection c=new ArrayList();
            c.add(new Student("kj",12));
            c.add(new Student("uj",13));
            c.add(new Student("tj",15));
            c.add(new Student("cj",14));
            
    //        Object[]ob= c.toArray();//将集合转换为数组
    //        
    //        for(int i=0;i<ob.length;i++){
    //            Student s=(Student)ob[i];
    //            System.out.println(s.getName()+"..."+s.getAge());
    //        }
               Iterator it=c.iterator();
               
               while(it.hasNext()){
                   Student s=(Student)it.next();
                   
    //               System.out.println(it.next());
                   System.out.println(s.getName()+"----"+s.getAge());
                   
               }
     
        }
    运行结果:

    kj----12
    uj----13
    tj----15
    cj----14
    其中,hasNext()方法,判断是否有下一个元素进行迭代,如果是则返回true,next()方法获取迭代的下一个元素。同toArray()一样,当操作子类的方法时,需要进行类型强转。Student s=(Student)it.next();

  • 相关阅读:
    Visual Studio 2019 使用.Net Core 3.0 一
    Asp.Net真分页技术
    Vue-员工管理系统
    Activex在没有电子秤api的情况下获取串口数据
    C#调用Activex中串口电子秤的数据,并将电子秤的数据显示到前端页面
    C# Datetime.Ticks
    Asp.Net进阶/管家模式+发布订阅模式:练习
    委托解耦
    Asp.Net进阶/值类型与引用类型:复习
    C# 简单日志帮助类LogHelper
  • 原文地址:https://www.cnblogs.com/lovelyYakir/p/5563675.html
Copyright © 2011-2022 走看看