增强for循环

Posted 罗贱人

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了增强for循环相关的知识,希望对你有一定的参考价值。

只适合取数据,只能用在数组、或实现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 , BlockingQueue , Deque , List , NavigableSet , Queue , Set , SortedSet , TransferQueue

所有已实现类: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 , BlockingQueue , Collection , Deque , DirectoryStream , List , NavigableSet , Path , Queue , SecureDirectoryStream , Set , SortedSet , TransferQueue

所有已实现的类: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循环的主要内容,如果未能解决你的问题,请参考以下文章

增强for循环

Java 增强for循环

增强for循环

增强for循环的使用详解及代码

for循环和for增强

增强的for循环