59. jdk1.5新特性之----增强for循环

/*
jdk1.5新特性之----增强for循环:底层是一个迭代器

作用:简化迭代器书写格式

使用范围:实现了Iterable接口的对象或者数组对象

格式:
    for(变量类型  变量名 :遍历目标){
        //代码块
    }
    
注意:
    1.因为for in循环底层还是迭代器,所以在循环的时候我们不能修改迭代对象的长度
    2.因为我们没有实例化迭代器对象,所以我们不能使用迭代器中的一些方法
*/

 

基本运用实例代码:

public class Demo2 {
    public static void main(String[] args) {
        //定义一个单列集合类
        HashSet<String> set = new HashSet<String>();
        set.add("狗娃 ");
        set.add("狗剩 ");
        set.add("铁蛋 ");
        //遍历单列集合类中的数据
        for(String item : set) {
            System.out.print(item);
        }
        
        System.out.println(" ");
        
        //定义一个数组
        int[] arr = {1,2,3};
        //遍历数组
        for(int item : arr) {
            System.out.print(item);
        }
            
    }
}

遍历双列集合

/*
注意:双列集合中没有实现Iterable接口

需求:用for in 遍历双列集合
*/
public class Demo3 {
    public static void main(String[] args) {
        HashMap<Integer,String> map = new HashMap<Integer,String>();
        map.put(1001,"狗蛋");
        map.put(1003,"狗剩");
        map.put(1002,"狗剩");
        
        //keySet:此映射中包含的键的 set 视图 (遍历键值)
        Set<Integer> set =  map.keySet();
        for(int item : set) {
            System.out.println(item);
        }
        
        //此映射中包含的映射关系的 set 视图 (键值对)
        Set<Entry<Integer, String>> set1 = map.entrySet();
        for(Entry<Integer, String> item : set1) {
            System.out.println(item);
        }
        
    }
}

猜你喜欢

转载自www.cnblogs.com/zjdbk/p/9021634.html