Java迭代器Iterator的底层

程序例子:

import java.util.Iterator;


/**
 * 
 * @author DELL
 *
 */
public class MyArrayList3 implements java.lang.Iterable{
	String[] elem = {"a","b","c","d","e","f","g"};
	int size = elem.length;
	

	/**
	 * 匿名内部类
	 * @return
	 */
	public Iterator iterator(){//Iterator类型的方法iterator()
		return new Iterator() {//匿名内部类		
			private int cursor = -1;	//游标或指针
			/**
			 * 判断是否存在下一个元素
			 * @return
			 */
			public boolean hasNext() {
				return cursor+1 it = list.iterator();
		
		while(it.hasNext()) {
			System.out.println(it.next());
			it.remove();	//迭代器好处可以在查看时删除元素
		}
		System.out.println("增强for,必须实现java.lang.Iterable接口,重写iterator方法");
		for(String temp:list) {
			System.out.println(temp);
		}
		
	}
}

Java迭代器Iterator的底层_第1张图片

你可能感兴趣的:(Java迭代器Iterator的底层)