ziyao

  博客园 :: :: 博问 :: 闪存 :: 新随笔 :: :: :: 管理 ::
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
 
import com.java.domain.Student;
 
/**
 * ArrayList 对自定义对象的遍历方法
 * @author jli31 *
 * ArrayList存储字符串并遍历,要求加入泛型,并用增强for遍历
 * 遍历方式:
 * A: 迭代器: Iterator i = list.iterator()
 * B: 普通for循环
 *          for (int i = 0; i<list.size(); i++)  list.get(i)
 *          for (Iterator i = list.iterator(); i.hasNext();)
 * C: 增强for玄幻
 *          for (String s : list)
 *
 * LinkedList, Vector, Collection, List 等存储遍历是完全一样的。
 */
 
publicclass ArrayListStudentTraversal {
     
      publicstaticvoid main(String[] args){
            //创建集合对象
            List<Student> studentList = new ArrayList<Student>();
           
            //创建自定义对象
            Student s1 = new Student(001, "李紫瑶", 1, 0);
            Student s2 = new Student(002, "Ivy", 27, 6000);
            Student s3 = new Student(003, "Ethan", 28, 10232);
           
            // 添加对象到集合
            studentList.add(s1);
            studentList.add(s2);
            studentList.add(s3);
           
            // 遍历集合 while + 迭代器
            Iterator<Student> it = studentList.iterator();
            System.out.println("**************** while -- Iterator**************");
            while(it.hasNext()){
                  Student s = it.next();
                  System.out.println(s);
            }           
            // 遍历集合 for 循环 + 迭代器
            System.out.println("**************** for -- Iterator**************");
            for(Iterator<Student> it1 = studentList.iterator(); it1.hasNext();){
                  Student s = it1.next();
                  System.out.println(s);
            }           
            // 遍历集合 for 循环
            System.out.println("**************** for **************");
            for(inti = 0; i<studentList.size(); i++){
                  Student s = studentList.get(i);
                  System.out.println(s);
            }           
            // 遍历集合  增强for
            System.out.println("**************** 增强for **************");
            for(Student s: studentList){
                  System.out.println(s);
            }           
      }
}
 

 

posted on 2017-02-16 20:22  ziyao  阅读(207)  评论(0编辑  收藏  举报