1. 程式人生 > >自定義迭代器 iterator介面

自定義迭代器 iterator介面

內部類方式

package guwa;

import java.util.Iterator;

public class MyArrayList2 {
	
	private String[] elem={"a","b","c","d","e"};
	private int size=elem.length;
	
	private class Item implements Iterator{
		private int cursor=-1;

		@Override
		public boolean hasNext() {
			return this.cursor+1<MyArrayList2.this.size;
		}

		@Override
		public Object next() {
			this.cursor++;
			return elem[cursor];
		}
		
	}
	
	public Iterator<String> iterator(){
		return new Item();
	}
	
	public static void main(String[] args) {
		MyArrayList2 my=new MyArrayList2();
		
		for(Iterator item=my.iterator();item.hasNext();){
			System.out.println(item.next());
		}
	}
	

	
}


匿名內部類方式

package guwa;

import java.util.Iterator;

public class MyArrayList3 {

	private String[] elem={"a","b","c","d","e"};
	private int size=elem.length;
	
	public Iterator<String> iterator(){
		return new Iterator<String>(){
			private int cursor=-1;

			@Override
			public boolean hasNext() {
				return this.cursor+1<MyArrayList3.this.size;
			}

			@Override
			public String next() {
				this.cursor++;
				return elem[cursor];
			}
			
		};
	}
	
	public static void main(String[] args) {
		MyArrayList3 my=new MyArrayList3();
		
		for(Iterator item=my.iterator();item.hasNext();){
			System.out.println(item.next());
		}
	}
}