码迷,mamicode.com
首页 > 其他好文 > 详细

增强for循环

时间:2018-02-19 23:47:02      阅读:305      评论:0      收藏:0      [点我收藏+]

标签:turned   loader   com   rem   copy   upd   queue   迭代器   nal   

只适合取数据,只能用在数组、或实现Iterable接口的集合类上。

List,Set,Map

List

`

public interface List<E>
extends Collection<E>

`

实现的类:AbstractList , AbstractSequentialList , ArrayList , AttributeList , CopyOnWriteArrayList , LinkedList , RoleList , RoleUnresolvedList , Stack , Vector


查看Collection接口

`

public interface Collection<E> extends Iterable<E>

`

子接口:BeanContext , BeanContextServices , BlockingDeque

所有已实现类:AbstractCollection , AbstractList , AbstractQueue , AbstractSequentialList , AbstractSet , ArrayBlockingQueue , ArrayDeque , ArrayList , AttributeList , BeanContextServicesSupport , BeanContextSupport , ConcurrentHashMap.KeySetView , ConcurrentLinkedDeque , ConcurrentLinkedQueue , ConcurrentSkipListSet , CopyOnWriteArrayList , CopyOnWriteArraySet , DelayQueue , EnumSet , HashSet , JobStateReasons , LinkedBlockingDeque , LinkedBlockingQueue , LinkedHashSet , LinkedList , LinkedTransferQueue , PriorityBlockingQueue , PriorityQueue , RoleList , RoleUnresolvedList , Stack , SynchronousQueue , TreeSet , Vector


查看Iterable接口

`

public interface Iterable<T>

`

子接口:BeanContext , BeanContextServices , BlockingDeque

所有已实现的类:AbstractCollection , AbstractList , AbstractQueue , AbstractSequentialList , AbstractSet , ArrayBlockingQueue , ArrayDeque , ArrayList , AttributeList , BatchUpdateException , BeanContextServicesSupport , BeanContextSupport , ConcurrentHashMap.KeySetView , ConcurrentLinkedDeque , ConcurrentLinkedQueue , ConcurrentSkipListSet , CopyOnWriteArrayList , CopyOnWriteArraySet , DataTruncation , DelayQueue , EnumSet , HashSet , JobStateReasons , LinkedBlockingDeque , LinkedBlockingQueue , LinkedHashSet , LinkedList , LinkedTransferQueue , PriorityBlockingQueue , PriorityQueue , RoleList , RoleUnresolvedList , RowSetWarning , SerialException , ServiceLoader , SQLClientInfoException , SQLDataException , SQLException , SQLFeatureNotSupportedException , SQLIntegrityConstraintViolationException , SQLInvalidAuthorizationSpecException , SQLNonTransientConnectionException , SQLNonTransientException , SQLRecoverableException , SQLSyntaxErrorException , SQLTimeoutException , SQLTransactionRollbackException , SQLTransientConnectionException , SQLTransientException , SQLWarning , Stack , SyncFactoryException , SynchronousQueue , SyncProviderException , TreeSet , Vector

实现了这个接口的集合对象支持迭代,是可迭代的。

https://www.cnblogs.com/keyi/p/5821285.html

一个集合对象要表明自己支持迭代,能有使用foreach语句的特权,就必须实现Iterable接口,表明我是可迭代的!然而实现Iterable接口,就必需为foreach语句提供一个迭代器。
这个迭代器是用接口定义的 iterator方法提供的。也就是iterator方法需要返回一个Iterator对象。

技术分享图片


Iterator接口

技术分享图片

技术分享图片

查看ArrayList里面的iterator()源码:

`

public Iterator<E> iterator() {
    return new Itr();
}

/**
 * An optimized version of AbstractList.Itr
 */
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() {
        return cursor != size;
    }

    @SuppressWarnings("unchecked")
    public E 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;
        return (E) elementData[lastRet = i];
    }

    public void 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();
        }
    }

    @Override
    @SuppressWarnings("unchecked")
    public void forEachRemaining(Consumer<? super E> consumer) {
        Objects.requireNonNull(consumer);
        final int size = ArrayList.this.size;
        int i = cursor;
        if (i >= size) {
            return;
        }
        final Object[] elementData = ArrayList.this.elementData;
        if (i >= elementData.length) {
            throw new ConcurrentModificationException();
        }
        while (i != size && modCount == expectedModCount) {
            consumer.accept((E) elementData[i++]);
        }
        // update once at end of iteration to reduce heap write traffic
        cursor = i;
        lastRet = i - 1;
        checkForComodification();
    }

    final void checkForComodification() {
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
    }
}

`


自定义StringList

`

public class StringList<E> implements Iterable<E>{
private int size;
transient Object[] elementData;
private static final Object[] EMPTY_ELEMENTDATA = {};
public StringList(Collection<? extends E> c){
    elementData = c.toArray();
    if ((size = elementData.length) != 0) {
        // c.toArray might (incorrectly) not return Object[] (see 6260652)
        if (elementData.getClass() != Object[].class)
            elementData = Arrays.copyOf(elementData, size, Object[].class);
    } else {
        // replace with empty array.
        this.elementData = EMPTY_ELEMENTDATA;
    }
}
public Iterator<E> iterator() {
    return new StringList.Itr();
}

private class Itr implements Iterator<E> {
    int cursor;
    int lastRet = -1;


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

    @Override
    public E next() {
        int i = cursor;
        if (i >= size)
            throw new NoSuchElementException();
        Object[] elementData = StringList.this.elementData;
        if (i >= elementData.length)
            throw new ConcurrentModificationException();
        cursor = i + 1;
        return (E) elementData[lastRet = i];
    }
}
}

`

`

public class TestStringList {
public static void main(String[] args) {
    List<String>list=new ArrayList<String>();
    list.add("AAAA");
    list.add("BBBB");
    list.add("CCCC");
    StringList<String> stringList=new StringList<String>(list);
    for (String str:stringList){
        System.out.println(str);
    }
}
}

`

结果:

技术分享图片

增强for循环

标签:turned   loader   com   rem   copy   upd   queue   迭代器   nal   

原文地址:https://www.cnblogs.com/rookieJW/p/8454612.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!