Collection遍历

 1 package test;
 2 
 3 
 4 import java.util.ArrayList;
 5 import java.util.Collection;
 6 import java.util.Iterator;
 7 
 8 
 9 
10 public class Test01 {
11     public static void main(String[] args) throws Exception {
12         Collection c=new ArrayList();
13         
14         Student s1=new Student("hello",22);
15         Student s2=new Student("world",22);
16         Student s3=new Student("哈哈",12);
17         Student s4=new Student("搜索",13);
18         
19         c.add(s1);
20         c.add(s2);
21         c.add(s3);
22         c.add(s4);
23         
24         //转为数组遍历
25         Object[] objs=c.toArray();
26         for(int x=0;x<objs.length;x++){
27             Student s=(Student)objs[x];
28             System.out.println(s.getName());
29         }
30         
31         //迭代器遍历
32         Iterator it=c.iterator();
33         while(it.hasNext()){
34             Student s=(Student)it.next();
35             System.out.println(s.getName());
36         }
37     }
38 }

 

 1 package test;
 2 
 3 
 4 import java.util.ArrayList;
 5 import java.util.Iterator;
 6 import java.util.List;
 7 
 8 
 9 
10 
11 
12 
13 public class Test01 {
14     public static void main(String[] args) throws Exception {
15         List list=new ArrayList();
16         
17         list.add("hello");
18         list.add("world");
19         list.add("java");
20         //list遍历方式1
21         Iterator it=list.iterator();
22         while(it.hasNext()){
23             String s=(String)it.next();
24             System.out.println(s);
25         }
26         //list遍历方式2
27         for(int x=0;x<list.size();x++){
28             String s=(String)list.get(x);
29             System.out.println(s);
30         }
31     }
32 }

 

posted @ 2015-08-24 16:06  chengling  阅读(581)  评论(0编辑  收藏  举报