【Java】Iterator底层原理,自己实现Iterator

package test;

import java.util.Iterator;

public class MyIterator implements java.lang.Iterable {
	
	private String[] element = {"a","b","c","d","e"};
	
	private int size = element.length;
	
	//匿名内部类
	public Iterator iterator(){
		return new Iterator(){
			//游标指针
			private int cursor = -1;
			
			/**
			 * 判断是否存在下一个元素
			 * @return
			 */
			public boolean hasNext() {
				return cursor+1 < size;
			}
			
			/**
			 * 获取下一个元素
			 * @param args
			 */
			public String next() {
				cursor++;
				return element[cursor];
			}
			
			/**
			 * 删除元素
			 * @param args
			 */
			public void remove() {
				
			}
		};
	}
	
	public static void main(String[] args) {
		MyIterator test = new MyIterator();
		Iterator it = test.iterator();
		
		while(it.hasNext()) {
			System.out.println(it.next());
		}
		
		//增强for,必须实现Iteralbe接口
		//不考虑下标
		for(String temp:test) {
			System.out.println(temp);
		}
	}
}

 

你可能感兴趣的:(java)