学习源码系列--- Iterable

根据官方当上阐述:
/**
 * Implementing this interface allows an object to be the target of
 * the "for-each loop" statement. See
 * <strong>
 * <a href="{@docRoot}/../technotes/guides/language/foreach.html">For-each Loop</a>
 * </strong>
 *
 * @param <T> the type of elements returned by the iterator
 *
 * @since 1.5
 * @jls 14.14.2 The enhanced for statement
 */

译文:

实现这个接口允许对象成为“for-each循环”语句的目标。

for-each循环的说明:

形如:

for (int i = 0; i < list.size; i ++) {
    Object obj = list.get(i);
}

可以简化成:

for (Object obj: list){
}

使用条件:

1、数组

      如果是简单的数组数据,则java会将foreach转换成for循环来执行;

2、实现了Iterable

      如果实现了Iterable接口的对象,那么在执行的时候,则是以迭代器的方式执行;

代码演示:

  数组版

编译前:
public class ForEach {
    public static void main(String[] args) {
        Object[] list = new Object[10];
        for (Object obj : list) {
            System.out.println(obj);
        }
    }
}


编译后:
public class ForEach {
    public ForEach() {
    }

    public static void main(String[] args) {
        Object[] list = new Object[10];
        Object[] var2 = list;
        int var3 = list.length;

        for(int var4 = 0; var4 < var3; ++var4) {
            Object obj = var2[var4];
            System.out.println(obj);
        }

    }
} 

在编译的时候还是将foreach转换成了简单的for循环

  对象版

编译前:
public class ForEach2 {
    public static void main(String[] args) {
        List<Object> list = new ArrayList<>();
        for (Object obj : list) {
            System.out.println(obj);
        }
    }
}
编译后:
public class ForEach2 {
    public ForEach2() {
    }

    public static void main(String[] args) {
        List<Object> list = new ArrayList();
        Iterator var2 = list.iterator();

        while(var2.hasNext()) {//检查序列中是否还有元素
            Object obj = var2.next();//返回当前数据,并指向下一元素
            System.out.println(obj);
        }
    }
}

实现了Iterable的对象,最后还是使用迭代器将数据一个一个遍历出来了

主要方法:

/**
 * Returns {@code true} if the iteration has more elements.//如果还有元素,返回true
 * (In other words, returns {@code true} if {@link #next} would
 * return an element rather than throwing an exception.)
 *
 * @return {@code true} if the iteration has more elements
 */
boolean hasNext();

  

/**
 * Returns the next element in the iteration.//返回迭代中的下一个元素
 *
 * @return the next element in the iteration
 * @throws NoSuchElementException if the iteration has no more elements
 */
E next();

  

/**
 * Removes from the underlying collection the last element returned
 * by this iterator (optional operation).//从基础集合中移除此迭代器返回的最后一个元素(可选操作) 
* This method can be called * only once per call to {@link #next}. The behavior of an iterator * is unspecified if the underlying collection is modified while the * iteration is in progress in any way other than by calling this * method. */ default void remove() { throw new UnsupportedOperationException("remove"); }

  

/**
 * Performs the given action for each remaining element until all elements
 * have been processed or the action throws an exception.  Actions are
 * performed in the order of iteration, if that order is specified.
 * Exceptions thrown by the action are relayed to the caller.
 *

default void forEachRemaining(Consumer<? super E> action) {
    Objects.requireNonNull(action);
    while (hasNext())
        action.accept(next());
}

参照ArrayList,写的迭代器:

public class SelfDefinationItrator<T> implements Iterable<T> {
    //定义一个初始数组
    private Object[] elementData = {};
    //用于空实例的共享空数组实例
    private static final Object[] EMPTY_ELEMENTDATA = {};
    //数组大小
    private int size = 0;

    public SelfDefinationItrator(int initialCapacity) {
        if (initialCapacity > 0) {
            this.elementData = new Object[initialCapacity];
        } else if (initialCapacity == 0) {
            this.elementData = EMPTY_ELEMENTDATA;
        } else {
            throw new IllegalArgumentException("Illegal Capacity: " +
                    initialCapacity);
        }
    }

    //添加
    public boolean add(T t) {
        if (size < elementData.length) {
            elementData[size] = t;
            size++;
            return true;
        } else {
            return false;
        }
    }

    @Override
    public Iterator<T> iterator() {
        return new ItrObject();
    }

    private class ItrObject implements Iterator<T> {
        //游标
        int point;

        @Override
        public boolean hasNext() {
            //如果、游标不等于大小,说明还有下一个
            return (point != size) ? true : false;
        }

        @Override
        public T next() {
            int i = point;
            if (i >= size)
                throw new RuntimeException();
            Object[] elementData = SelfDefinationItrator.this.elementData;
            if (i >= elementData.length)
                throw new RuntimeException();
            point = i + 1;
            return (T) elementData[i];
        }
    }

  测试:

  public static void main(String[] args) {
        SelfDefinationItrator<String>  selfDefinationItrator = new SelfDefinationItrator<String>(3);
        selfDefinationItrator.add("a");
        selfDefinationItrator.add("b");
        selfDefinationItrator.add("c");
        System.out.println(selfDefinationItrator.add("d"));
        for (String ss :selfDefinationItrator) {
            System.out.println(ss);
        }
    }

  

 

 

 

 

 

/**
 * Performs the given action for each remaining element until all elements
 * have been processed or the action throws an exception.  Actions are
 * performed in the order of iteration, if that order is specified.
 * Exceptions thrown by the action are relayed to the caller.
 *
 * @implSpec
 
* <p>The default implementation behaves as if:

posted @ 2019-04-30 22:48  Kill(Bug)  阅读(41)  评论(0)    收藏  举报