Iterator底层源码分析

/**
* Iterator用于遍历Collection下的集合,Collection下的每个集合底层实现不一样,意味着遍历逻辑也不一样,
* 所以Java的设计者将Iterator设计成了接口,让Collection下的每个集合实现Iterator
*/
public interface Iterator<E> {
    //判断是否有可迭代的元素
    boolean hasNext();

   	//返回下一个元素
    E next();

    //删除(默认方法) -- 报错
    default void remove() {
        throw new UnsupportedOperationException("remove");
    }
}
public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {
	//外部操作数(记录集合添加、删除的次数)
	protected transient int modCount = 0;//6
}
public class ArrayList<E> extends AbstractList<E> implements List<E>{
	
    //数据容器 - ["aaa","ccc","ddd","eee",null,null,null,null,null,null]
    transient Object[] elementData;
    //数据个数(指针)
    private int size;//4

    //e - "eee"
	public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // 判断是否扩容
        elementData[size++] = e;
        return true;
    }
    
    private void ensureCapacityInternal(int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }
        ensureExplicitCapacity(minCapacity);
    }
    
    private void ensureExplicitCapacity(int minCapacity) {
        modCount++;

        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }
    
    //o - "bbb"
    public boolean remove(Object o) {
        if (o == null) {
            for (int index = 0; index < size; index++)
                if (elementData[index] == null) {
                    fastRemove(index);
                    return true;
                }
        } else {
            //线性查询(从头遍历到size的位置)
            for (int index = 0; index < size; index++)
                if (o.equals(elementData[index])) {
                    //删除元素(传入下标)
                    fastRemove(index);
                    return true;
                }
        }
        return false;
    }
    
    //index - 1
    private void fastRemove(int index) {
        modCount++;
        int numMoved = size - index - 1;//计算移动次数
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index, numMoved);
        elementData[--size] = null; // clear to let GC do its work
    }
    
    public Iterator<E> iterator() {
        return new Itr();
    }
    
    //Itr是成员内部类,因为Itr中使用到了外部类(ArrayList)的成员属性(modCount、size)
    private class Itr implements Iterator<E> {
        int cursor;       // 游标 - 4
        int lastRet = -1; // 当前元素的下标 - 3
        int expectedModCount = modCount;//内部操作数 - 6

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

        @SuppressWarnings("unchecked")
        public E next() {
            checkForComodification();//判断外部操作数和内部操作数是否相同
            int i = cursor;//i = 3
            if (i >= size)
                throw new NoSuchElementException();
            //elementData - ["aaa","ccc","ddd","eee",null,null,null,null,null,null]
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1;//cursor - 4
            return (E) elementData[lastRet = i];
        }
        
        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }

        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();//判断外部操作数和内部操作数是否相同

            try {
                //Itr依赖于ArrayList对象的remove()去删除元素
                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();
        }

        
    }
}
ArrayList<String> list = new ArrayList<>();
		
list.add("aaa");
list.add("bbb");
list.add("ccc");
list.add("ddd");
list.add("eee");

list.remove("bbb");

Iterator<String> it = list.iterator();
while(it.hasNext()){
    String element = it.next();
    System.out.println(element);
}

注意:看源码找场景

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值