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

来源:互联网 发布:php超市会员管理系统 编辑:程序博客网 时间:2024/05/18 17:41

引入增强for循环的原因:在JDK5以前的版本中,遍历数组或集合中的元素,需先获得数组的长度或集合的迭代器,比较麻烦!
因此JDK5中定义了一种新的语法——增强for循环,以简化此类操作。增强for循环只能用在数组、或实现Iterable接口的集合类上

语法格式:

for(变量类型 变量 :需迭代的数组或集合){}

For each是为了让你的代码变得简捷、和容易维护。


增强for循环要注意的细节:
1. 迭代器可以对遍历的元素进行操作,使用增强for循环时,不能对集合中的元素进 行操作的。
2. 增加for循环与普通的for循环区别。
3. map的遍历。

增强for循环要注意的事项:
1. 增强for循环底层也是使用了迭代器获取的,只不过获取迭代器由jvm完成,不需要我们获取迭代器而已,所以在使用增强for循环变量元素的过程中不准使用集合对象对集合的元素个数进行修改。
2. 迭代器遍历元素与增强for循环变量元素的区别:使用迭代器遍历集合的元素时可以删除集合的元素,而增强for循环变量集合的元素时,不能调用迭代器的remove方法删除元素。
3. 普通for循环与增强for循环的区别:普通for循环可以没有变量的目标,而增强for循环一定要有变量的目标。

public class App {    public static void main(String[] args) {        HashSet<String> set = new HashSet<String>();        //添加元素        set.add("狗娃");        set.add("狗剩");        set.add("铁蛋");        /*        //使用迭代器遍历Set的集合.        Iterator<String> it  = set.iterator();        while(it.hasNext()){            String temp = it.next();            System.out.println("元素:"+ temp);            it.remove();        }        //使用增强for循环解决        for(String item : set){            System.out.println("元素:"+ item);        }        /* 数组 */        int[] arr = {12,5,6,1};        // 普通for循环的遍历方式        for(int i =  0 ; i<arr.length ; i++){            System.out.println("元素:"+ arr[i]);        }        //使用增强for循环实现        for(int item :arr){            System.out.println("元素:"+ item);        }        //需求: 在控制台打印5句hello world.        for(int i = 0 ; i < 5; i++){            System.out.println("hello world");        }        */        //注意: Map集合没有实现Iterable接口,所以map集合不能直接使用增强for循环,如果需要使用增强for循环需要借助于Collection        // 的集合。        HashMap<String, String> map = new HashMap<String, String>();        map.put("001","张三");        map.put("002","李四");        map.put("003","王五");        map.put("004","赵六");        Set<Map.Entry<String, String>> entrys = map.entrySet();        for(Map.Entry<String, String> entry  :entrys){            System.out.println("键:"+ entry.getKey()+" 值:"+ entry.getValue());        }    }}

通过以上的例子说明,只要一个类实现了Iterable接口,就可以使用增强for循环!
我们可以自定义一个类来实现Iterable接口:


package cn.jdk15;import java.util.Iterator;//自定一个类使用增强for循环class MyList implements Iterable<String>{    Object[] arr = new Object[10];    int index = 0 ; //当前的指针    public void add(Object o){        arr[index++] = o;  //     }    public int size(){        return index;    }    @Override    public Iterator<String> iterator() {        //使用了匿名内部类        return new Iterator<String>() {            int cursor  = 0;            @Override            public boolean hasNext() {                return cursor<index;            }            @Override            public String next() {                return (String) arr[cursor++];            }            @Override            public void remove() {            }        };    }}public class Demo {    public static void main(String[] args) {        MyList list = new MyList();        list.add("张三");        list.add("李四");        list.add("王五");        for(String item :list){            System.out.println(item);        }    }}

实现Iterable接口要实现接口里面的所有方法,hasNext() 、next() 、 remove() 这三个方法,我们参考jdk源码,在类List类中它就实现了Iterable接口,让我们看看sun公司是怎么写的:

 private class Itr implements Iterator<E> {        int cursor;       // index of next element to return        int lastRet = -1; // index of last element returned; -1 if no such        int expectedModCount = modCount;        public boolean hasNext() { //hasNext方法            return cursor != size;        }        @SuppressWarnings("unchecked")        public E next() { // next方法            checkForComodification();            int i = cursor;            if (i >= size)                throw new NoSuchElementException();            Object[] elementData = ArrayList.this.elementData;            if (i >= elementData.length)                throw new ConcurrentModificationException();            cursor = i + 1;  //游标加1操作            return (E) elementData[lastRet = i];        }        public void remove() {//remove方法            if (lastRet < 0)                throw new IllegalStateException();            checkForComodification();            try {                ArrayList.this.remove(lastRet);                cursor = lastRet;                lastRet = -1;                expectedModCount = modCount;            } catch (IndexOutOfBoundsException ex) {                throw new ConcurrentModificationException();            }        }

可以根据自己的定义的类的实际情况编写自己的方法。


2017年12月16日 21:22:48