Iterable介面

u010660276發表於2014-01-04

Iterable介面包含一個產生Iterator的iterator的方法,用於foreach中移動

下面是一個例子:

import java.util.*;
public class IteratableClass implements Iterable<String>{
	protected String [] words="and that is how we know the earth to be banana-shaped".split(" ");
	public Iterator<String> iterator(){
		return new Iterator<String>(){
			private int index=0;
			public boolean hasNext(){
				return index<words.length;
			}
			public String next(){
				return words[index++];
			}
			public void remove(){
				
			}
		};
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		for(String s:new IteratableClass()){
			System.out.println(s+" ");
		}

	}

}

下面用介面卡方法產生反向的迭代的方法:

import java.util.*;
public class ReversibleArrayList<T> extends ArrayList<T>{
	public ReversibleArrayList(Collection<T> c){
		super(c);
	}
	public Iterable<T> reversed(){
		return new Iterable<T>(){
			public Iterator<T> iterator(){
				return new Iterator<T>(){
					int current=size()-1;
					public boolean hasNext(){
						return current>0;
					}
					public T next(){
						return get(current--);
					}
					public void remove(){}
				};
			}
		};
	}

}

import java.util.*;
public class AdapterMethodIdiom {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ReversibleArrayList<String> ral=new ReversibleArrayList<String>(Arrays.asList("to be or not to be".split(" ")));
		for(String s:ral)
			System.out.print(s+" ");
		System.out.println();
		for(String s:ral.reversed())
			System.out.print(s+" ");

	}

}




相關文章