• Java 集合——遍历


    Iterator和foreach;

    先给Student类:

    package com.xuyigang1234.chp06.sec01;
    
    public class Student {
        private String name;
        private int age;
        
        public Student(String name, int age) {
            super();
            this.name = name;
            this.age = age;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public int getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }
        
    }

    遍历:

    package com.xuyigang1234.chp06.sec01;
    
    import java.util.Iterator;
    import java.util.LinkedList;
    
    public class TestIterator {
        public static void main(String[] args) {
            LinkedList<Student> list = new LinkedList<Student>();
            list.add(new Student("小白",10));
            list.add(new Student("小红",14));
            list.add(new Student("小黑",12));
            //用Iterator遍历
            Iterator<Student> it = list.iterator(); //返回迭代器
            while(it.hasNext()) {
                Student s=it.next(); //返回迭代的下一个元素
                System.out.println("姓名:"+s.getName()+",年龄:"+s.getAge());
            }
            System.out.println("----------------------------");
            //用 foreach遍历
            for(Student s:list) {
                System.out.println("姓名:"+s.getName()+",年龄:"+s.getAge());
            }
        }
    }
    姓名:小白,年龄:10
    姓名:小红,年龄:14
    姓名:小黑,年龄:12
    ----------------------------
    姓名:小白,年龄:10
    姓名:小红,年龄:14
    姓名:小黑,年龄:12
    
  • 相关阅读:
    Spring 控制反转容器(Inversion of Control – IOC)
    理解依赖注入(DI
    创建一个简单的Spring应用
    Spring开发环境搭建(Eclipse)
    Spring框架模块
    Spring 框架介绍
    spring教程
    Bulma CSS
    Bulma CSS
    Bulma CSS
  • 原文地址:https://www.cnblogs.com/xyg-zyx/p/10007390.html
Copyright © 2020-2023  润新知