for循环遍历集合的底层原理

1、为什么集合不能像数组那样遍历

集合分为单列集合Collection和双列集合Map。其中,Collection中没有和索引值相关的类型,所以不能直接用for循环按照索引去遍历。
集合大体可以分为:
在这里插入图片描述

2、迭代器使用方法

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

3、增强for循环

for(String s:list){
	System.out.println(s);
}

4、增强for循环的底层原理

不同的集合类型有不同的覆盖方法,以ArrayList为例。
增强for循环的底层使用的也是迭代器原理,查看源码:

public Iterator<E> iterator() {
        return new 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];
        }

简单概括增强for循环底层做了哪些事情:

public class ArrayList<E> {
	private int size;
	private Object[] elemData;
	
	//定义一个成员内部类
	private class Itr<E> implements Iterator<E>{
		int cursor;
		@Override
		public boolean hasNext() {
			return cursor!=size;
		}

		@Override
		public E next() {
			return (E) elemData[cursor++];
		}
	}
}

(1)创建Itr类,实现Iterator接口,覆盖重写hasNext()和next()方法
(2)重写hasNext():用当前游标所指位置的索引值和集合中元素个数进行比较,判断当前是否还有元素
(3)重写next():若有元素,就读取当前元素,游标后移一位

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值