Java集合(二)--Iterator和Iterable

Iterable:
public interface Iterable<T> {
    Iterator<T> iterator();
}

上面是Iterable源码,只有一个iterator(),所以Iterable接口只是用来返回一个新的迭代器,意味着这个集合支持迭代

Collection是list和set的父接口,而Collection实现了Iterable,所以list和set都可以使用迭代器

Iterator:
public interface Iterator<E> {
    boolean hasNext();

    E next();

}

例如ArrayList的使用,只不过这里是向上转型,返回list,而不是ArrayList

public static void main(String[] args) {
	List<Integer> list = Arrays.asList(1, 2, 3);
	Iterator iterator = list.iterator();
	while (iterator.hasNext()) {
		System.out.println(iterator.next());
	}
}

而如果使用ArrayList<Integer> list = new ArrayList<>();去使用迭代器,返回的是ArrayList内部维护的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();
		}
	}      
}
ListIterator:

  ListIterator只能用于list的迭代,可以双向移动

public static void main(String[] args) {
	List<Integer> list = new ArrayList<>();
	ListIterator iterator = list.listIterator();
	while (iterator.hasPrevious()) {
		System.out.println(iterator.previous());
	}
	while (iterator.hasNext()) {
		System.out.println(iterator.next());
	}
}
为什么一定要实现Iterable接口,为什么不直接实现Iterator接口呢?

以下解答来自百度,很多文章都是这样写的,具体出处我也找不到了

  因为Iterator接口的核心方法next()或者hasNext()是依赖于迭代器的当前迭代位置的。 如果Collection直接实现Iterator接口,势必导致集合

对象中包含当前迭代位置的数据(指针)。 当集合在不同方法间被传递时,由于当前迭代位置不可预置,那么next()方法的结果会变成不可预知。 除

非再为Iterator接口添加一个reset()方法,用来重置当前迭代位置。 但即时这样,Collection也只能同时存在一个当前迭代位置。 

  而Iterable则不然,每次调用都会返回一个从头开始计数的迭代器。 多个迭代器是互不干扰的。 

转载于:https://www.cnblogs.com/huigelaile/p/11042520.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值