ArrayList遍历的三种方法

在输出很多的ArrayList的元素时,用普通的for循环太麻烦,因此本文介绍三种遍历ArrayList的方法

package test;

public class Student {
        private String name;
        private int age;
    public Student() {
        // TODO Auto-generated constructor stub
    }
    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;
    }
    public Student(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }

}

用Student类来定义学生,有两个属性,姓名,年龄,以及get,set方法,还有构造方法。

package test;

import java.util.ArrayList;
import java.util.Iterator;
import test.Student;

public class test {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ArrayList<Student> list = new ArrayList<Student>();
        list.add(new Student("张三", 10));
        list.add(new Student("李四", 10));
        list.add(new Student("王五", 10));

//    第一种遍历方法
        System.out.println("第一种遍历方法普通for循环");
        for (int i = 0; i < list.size(); i++) {
            Student s = list.get(i);
            System.out.println("姓名:" + s.getName() + "年龄" + s.getAge());
        }

//    第二种遍历方法
        System.out.println("第二种遍历方法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());
        }

    }

}

 通过运行结果发现,结果一模一样,但是看代码的话,第三种代码比前两种要简单得多,因此如果熟练要尽可能的用简单的方式

猜你喜欢

转载自www.cnblogs.com/tkg1314/p/11964054.html
今日推荐