java :四器 之 迭代器初学

package GeneIterAdaptReflect.com;
import java.util.*;


/*
 * 第一:java.lang. Iterable接口
 *      //实现这个接口,运行对象成为forEach语句的目标;
 *      interface Iterable<T>{
 *          //返回一个在 一组T类型的元素上 进行迭代的迭代器;
 *          Iterator<T> iterator();
 *      }
 *      注释:实现这个接口允许对象成为 "foreach" 语句的目标。这样就可以类似使用数组那样,用foreach语句来遍历所有有关的对象,
 *          但是对于自定义的类型和其实例对象,想要使用foreach语句来遍历它本身集体的话,可能就要实现Iterable<T>接口了。
 * 
 * 第二:java.util.Iterator接口
 *      //对 collection 进行迭代的迭代器。迭代器取代了 Java Collections Framework 中的 Enumeration。
 *      //迭代器与枚举有两点不同: 迭代器允许调用者利用定义良好的语义在迭代期间从迭代器所指向的 collection 移除元素。 
                           方法名称得到了改进。 
 *      interface Iterator<E>{
 *          boolean hasNext();
 *          E next();
 *          //remove 可选操作,从迭代器指向的 collection 中移除迭代器返回的最后一个元素
 *          void remove();
 *      }
 * 通过以下两个例子来展现iterator的用法;
 *      首先理解下为什么存在迭代器;
 *      迭代器就是集合取出元素的方式;
 *      因为每个容器都有 存和取的功能,由于每个容器的数据存储结构不同,其存和取的方式也就不同;而对于取出元素,其不止一个动作来完成(先判断 再取等多个动作)
 *      那么这多个动作就应该封装成一个对象;这样每个容器中就都有一个取出数据的对象;因为不同容器的数据结构不同,因此每个容器中取出对象的实现方式也不一样;
 *      那么就应该在每个容器内部 定义一个取出元素的内部类(因为数据就存在这个容器中,直接用内部类来操作这些数据时最方方便的,因此用内部类),但是这些取出
 *      的内部类有自己的共性东西 都有 判断和取出。因此就可以向上抽取成一个接口(Iterator)
 * 
 *      对内部类的理解和迭代器设计模式的理解:
 *          内部类: 容器是一个事物,而容器内部存储的东西也是一个事物,那么就可以定一个内部类在容器内操容器内的事物;
 *          迭代器设计模式:多个类都有自己操作其内部数据的方式,而这些方式又有相同的共性,那么就可以把这个共性抽取成一个接口,在各个类中提供一个方法
 *                     来返回这个接口,通过这个接口(进而通过内部类)来操作这多个类中的数据;
 * 
 *      源代码:
 *          看ArrayList中的iterator设计方式;由于ArrayList 和 LinkedList 继承与AbastractList类
 * 
 * public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {
 *       public Iterator<E> iterator() {
 *          return new Itr();
 *      }
 *      //内部类
 *      private class Itr implements Iterator<E> {
 *          int cursor = 0;
 *          int lastRet = -1;
 *          int expectedModCount = modCount;

            public boolean hasNext() {
                return cursor != size();
            }

            public E next() {
                checkForComodification();
                try {
                    int i = cursor;
                    E next = get(i);
                    lastRet = i;
                    cursor = i + 1;
                    return next;
                } catch (IndexOutOfBoundsException e) {
                    checkForComodification();
                    throw new NoSuchElementException();
                }
            }

            public void remove() {
                if (lastRet < 0)
                    throw new IllegalStateException();
                checkForComodification();

                try {
                    AbstractList.this.remove(lastRet);
                    if (lastRet < cursor)
                        cursor--;
                    lastRet = -1;
                    expectedModCount = modCount;
                } catch (IndexOutOfBoundsException e) {
                    throw new ConcurrentModificationException();
                }
            }

            final void checkForComodification() {
                if (modCount != expectedModCount)
                    throw new ConcurrentModificationException();
            }
        }
 *  }
 * }    
 *  
 * 
 *      对代码书写的理解:
 *          Iterator it = list.iterator();
 *          while(it.hasNext())
 *              sop(it.next());
 *          while循环 it这个对象在迭代器方法完成后并没有立刻释放,仍旧占用内存;
 *          
 *          for(Iterator it = list.iterator();it.hasNext();)
 *                  sop(it.next());
 *          for的好处在于把it弄成了局部变量 方法完成 也就马上释放了 推荐写法;
 *
 *      实例1:Collection 和  Iterator
 *          因为iterator是超接口Collection中的方法,那么实现Collection的子类,必定重写了iterator;
 *      实例2:定义一个自己的 并通过Iteratro来取出成员
 * 
 * 
 * */

//实例1:

class CollectionAndIterator {

    String[] infos = "hello java : wo should say hello to the world !!".split(" ");

    List<String> infoList = Arrays.asList(infos);

    public void showForeach(){
        for(String str:infoList){
            System.out.print(str+" ");
        }
    }
    public void showDefaultIterator(){
        for(Iterator<String> it = infoList.iterator();it.hasNext();){
            System.out.print(it.next()+" ");
        }
    }
    public void showReverseIterator(){
        ReverseIteratorList<String> ris = new ReverseIteratorList<String>(infoList);
        for(Iterator<String> it = ris.reverseIterator();it.hasNext();)
            System.out.print(it.next()+" ");
    }
    @SuppressWarnings("serial")
    private class ReverseIteratorList<T> extends ArrayList<T>{
        private Collection<T> c=null;

        ReverseIteratorList(Collection<T> c){
            super(c);
            this.c = c;
        }
        private Iterator<T> reverseIterator(){
            return new Iterator<T>(){
                int current = c.size()-1;
                public boolean hasNext(){
                    return current>-1;
                }
                public T next(){
                    return get(current--);
                }
            };
        }
    }

}

public class IteratorTest {

    public static void main(String[] args) {
        CollectionAndIterator cai = new CollectionAndIterator();
        System.out.print("foreach: ");
        cai.showForeach();
        System.out.println();

        System.out.print("defaultIterator: ");
        cai.showDefaultIterator();
        System.out.println();

        System.out.print("resvereIterator: ");
        cai.showReverseIterator();
    }
}











  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值