Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.util.Collection;

import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

import java.util.Vector;

public class Main {
    /**
     * Gets the reverse iterable of an Iterable (i.e. a collection).
     * If this collection implements ListIterator, then this operation is far more efficent.
     * Otherwise, the iterable is iterated through, where the results are stored, before
     * returning a iterable that iterates through the resulting list.
     * 
     * @param it
     * @return
     */
    public static <T> Iterable<T> getReverse(Iterable<T> it) {
        if (it instanceof List) { //list takes up less computation and memory - use built in list iterator
            final ListIterator<T> iter = ((List<T>) it).listIterator(((List<T>) it).size());
            return new Iterable<T>() {
                public Iterator<T> iterator() {
                    return getReverseIterator(iter);
                }
            };
        }

        int size = 10;
        if (it instanceof Collection) { //if not a list, but is a collection
            size = ((Collection<T>) it).size();
        }
        List<T> list = new Vector<>(size);
        for (T t : it) {
            list.add(t);
        }
        final ListIterator<T> iter = list.listIterator(list.size());

        return new Iterable<T>() {
            public Iterator<T> iterator() {
                return getReverseIterator(iter);
            }
        };
    }

    public static <T> Iterator<T> getReverseIterator(final ListIterator<T> iter) {
        return new Iterator<T>() {
            public boolean hasNext() {
                return iter.hasPrevious();
            }

            public T next() {
                return iter.previous();
            }

            public void remove() {
                iter.remove();
            }
        };
    }
}