黑马程序员技术交流社区

标题: List集合三种遍历方式 [打印本页]

作者: hero_king    时间: 2016-5-29 23:10
标题: List集合三种遍历方式
由于List集合特有方法get方法的存在,所以list集合有三种遍历方式
学生类就不放上来了,就一个name一个age属性。
  1. <p>public class Demo2 {
  2. public static void main(String[] args) {
  3.   List<Student> list = new ArrayList<>();
  4.   Student s1 = new Student("小明", 27);
  5.   Student s2 = new Student("张三", 28);
  6.   Student s3 = new Student("李四", 22);
  7.   list.add(s1);
  8.   list.add(s2);
  9.   list.add(s3);
  10.   // 第一种:普通for遍历
  11.   for (int i = 0; i < list.size(); i++) {
  12.    System.out.println(list.get(i).getName() + "--"
  13.      + list.get(i).getAge());
  14.   }
  15.   
  16.   // 第二种:迭代器遍历
  17.   Iterator<Student> it = list.iterator();
  18.   while (it.hasNext()) {
  19.    Student s = it.next();
  20.    System.out.println(s.getName() + "---" + s.getAge());
  21.   }
  22.   
  23.   // 第三种方法:增强for遍历:底层是迭代器
  24.   for (Student s : list) {
  25.    System.out.println(s.getName() + "---" + s.getAge());
  26.   }</p><p> }
  27. }
  28. </p><p> </p>
复制代码


作者: hmCEO    时间: 2016-5-29 23:20
谢谢,写的不错




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2