JDK 1.5 新特性——增强for循环

  简单的介绍。

View Code
 1 public class ForEach {
 2 
 3     /**
 4      * @author yokoboy
 5      *  2012年7月24日
 6      */
 7     public static void f1(int[] a) {
 8         for (int i = 0; i < a.length; i++) {
 9             System.out.println(a[i]);
10         }
11     }
12 
13     public static void f2(int[] a) {
14         for (int i : a) {
15             System.out.println(i);
16         }
17     }
18 
19     public static void main(String[] args) {
20         int[] a1 = {1, 2, 3, 4};
21         f1(a1);//传统for循环
22         f2(a1);//增强for循环
23     }
24 }

 

  还有就是只要实现Iterable<E>接口的都可用增强for循环进行迭代,例如,ArrayList<E>,HashSet<E>等,

需要注意的是Map<K,V>不能直接用增强for循环,因为Map家族并没有实现Iterable<E>接口。

View Code
 1 import java.util.ArrayList;
 2 import java.util.Iterator;
 3 
 4 public class ForEach {
 5 
 6     /**
 7      * @author yokoboy
 8      *  2012年7月24日
 9      */
10     public static void f1(ArrayList a) {
11         for (Iterator it = a.iterator(); it.hasNext();) {
12             System.out.println(it.next());
13         }
14     }
15 
16     public static void f2(ArrayList a) {
17         //这里ArrayList没用泛型,所以不知道里面存的是什么对象,只能用Object来接
18         for (Object s : a) {
19             System.out.println((String) s);//强制类型转换成String,用泛型就不用这样了
20         }
21     }
22 
23     public static void main(String[] args) {
24         ArrayList al = new ArrayList();
25         al.add("one");
26         al.add("two");
27         al.add("three");
28         f1(al);//传统for循环
29         f2(al);//增强for循环
30     }
31 }

 

  下面介绍,Map怎样用增强for循环。

View Code
 1 import java.util.HashMap;
 2 import java.util.Map;
 3 import java.util.Set;
 4 
 5 public class ForEach {
 6 
 7     /**
 8      * @author yokoboy
 9      *  2012年7月24日
10      */
11     public static void f1(Map<String, String> a) {
12         Set<String> ss = a.keySet();
13         for (String s : ss) {
14             System.out.println(s + "::" + a.get(s));
15         }
16     }
17 
18     public static void f2(Map<String, String> a) {
19         Set<Map.Entry<String, String>> ss = a.entrySet();
20         for (Map.Entry<String, String> s : ss) {
21             System.out.println(s.getKey() + "::" + s.getValue());
22         }
23     }
24 
25     public static void main(String[] args) {
26         Map<String, String> al = new HashMap<String, String>();
27         al.put("one", "haha");
28         al.put("two", "hehe");
29         al.put("three", "heihei");
30         f1(al);//传统for循环
31         f2(al);//增强for循环
32     }
33 }

 

 

鸣谢:毕向东老师,带我走进了java的世界。 O(∩_∩)O~

 

转载请注明出处:

博客园_yokoboy

http://www.cnblogs.com/yokoboy/archive/2012/07/24/2607425.html

 

posted @ 2012-07-24 23:00  yokoboy  阅读(1127)  评论(0编辑  收藏  举报
yokoboy