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);
        }
    }

}

 

相关文章:

  • 2021-08-30
  • 2021-05-04
  • 2021-11-21
  • 2021-09-01
  • 2021-12-23
  • 2022-12-23
  • 2022-01-21
猜你喜欢
  • 2022-03-03
  • 2021-06-01
  • 2022-12-23
  • 2021-11-28
  • 2021-12-22
  • 2021-09-13
  • 2021-08-12
相关资源
相似解决方案