Java集合(二)--Iterator和Iterable

时间:2019-06-17
本文章向大家介绍Java集合(二)--Iterator和Iterable,主要包括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