首页 > 技术文章 > For-Each循环

foxspecial 2013-08-06 22:06 原文

 

For-Each循环也叫增强型的for循环,或者叫foreach循环。

For-Each循环是JDK5.0的新特性(其他新特性比如泛型、自动装箱等)。

For-Each循环的加入简化了集合的遍历。

语法如下:

for(type element: array){  System.out.println(element);   }
 
 

Demo:

      public static void query()
      {
        List<Teacher> list = new ArrayList<Teacher>(); //list里存的是N个Teacher对象
        System.out.println("*****方式一*******"); //第一种方式 普通for循环 
        for(int i=0;i<list.size();i++)
        { Teacher t = (Teacher)list.get(i); 
        System.out.println(t.getName()); }
 
        System.out.println("*****方式二*******"); //第二种方式 使用迭代器 
        for(Iterator<Teacher> iter = list.iterator(); iter.hasNext();)
        { System.out.println(iter.next().getName()); }  
        System.out.println("*****方式三*******"); //第三种方式 增强型for循环
        for(Teacher t: list){ System.out.println(t.getName()); } }

For-Each循环的缺点:丢掉了索引信息。

当遍历集合或数组时,如果需要访问集合或数组的下标,那么最好使用旧式的方式来实现循环或遍历,而不要使用增强的for循环,因为它丢失了下标信息。

优点还体现在泛型 假如 set中存放的是Object

Set<Object> set = new HashSet<Object>();
for循环遍历:
  for (Object obj: set) {
       if(obj instanceof Integer){
                 int aa= (Integer)obj;
              }else if(obj instanceof String){
                String aa = (String)obj
              }
               ........
  }
如果你用Iterator遍历,那就晕了
map list 也一样
唯一的缺点就是 在遍历 集合过程中,不能对集合本身进行操作
   for (String str : set) {
    set.remove(str);//错误!
   }

推荐阅读