迭代器为啥不定义一个类而不是一个接口

  因为不同集合的数据结构和存储方式不同,所以遍历也不同。

假迭代器定义为一个类,首先若是具体类那么就会提供一个公共的实现不同集合遍历的方法,我们知道这是不可能的。
若是一个抽象类又因为java中类是单继承的所以无法同时继承多个类所以不行而且集合的根接口无法继承抽象类
其实迭代器的具体实现方法是在集合的具体子类中以内部类的方式实现。

具体子类中以内部类的方式实现的源码

public interface Inteator {
	boolean hasNext();
	Object next(); 
}

public interface Iterable {
    Iterator iterator();
}

public interface Collection extends Iterable {
	Iterator iterator();
}

public interface List extends Collection {
	Iterator iterator();
}

public class ArrayList implements List {
	public Iterator iterator() {
        return new Itr();
    }
    
    private class Itr implements Iterator {//实现Iterator接口的具体类
    	public boolean hasNext() {
            //实现hasNext的方法体
        }
		public Object next(){
            //实现next的方法体
        } 
    }
}


Collection c = new ArrayList();

Iterator it = c.iterator();	 //new Itr();
while(it.hasNext()) {
	
	System.out.println(it.next());
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值