匿名内部类 , Iterable<T> 和 Iterator<T>

package generic;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;

public class ReversibleArrayList<T> extends ArrayList<T> {
    private static final long serialVersionUID = -2293646393609696016L;
    
    public ReversibleArrayList(Collection<T> collection){
        super(collection);
    }
    
    public Iterable<T> reversed(){
        return new Iterable<T>() {

            @Override
            public Iterator<T> iterator() {
                return new Iterator<T>() {
                    int idx = ReversibleArrayList.this.size() - 1;

                    @Override
                    public boolean hasNext() {
                        return idx > -1;
                    }

                    @Override
                    public T next() {
                        return ReversibleArrayList.this.get(idx--);
                    }

                    @Override
                    public void remove() {
                        throw new UnsupportedOperationException();                        
                    }                    
                };
            }
            
        };
    }
    
    public static void main(String[] args) {
        ReversibleArrayList<String> list = new ReversibleArrayList<String>(
                Arrays.asList("To be or not to be".split(" ")));
        
        for (String s : list) {
            System.out.println(s);
        }
        
        System.out.println("----------------");
        
        for (String s : list.reversed()) {
            System.out.println(s);
        }
    }

}

 

posted @ 2014-08-26 13:12  庚武  Views(491)  Comments(0Edit  收藏  举报