1. 程式人生 > >Java 集合——遍歷

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