Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2006, 2014 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Mike Kucera (IBM Corporation) - initial API and implementation
 *     Sergey Prigogin (Google)
 *     Nathan Ridge
 *******************************************************************************/

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

public class Main {
    /**
     * Allows a foreach loop to iterate backwards over a list from the end to the start.
     * 
     * <p>
     * Example use:
     * <pre>
     *     for (Object o : reverseIterable(list)) { ... }
     * </pre>
     * 
     * @throws NullPointerException if list is null
     */
    public static <T> Iterable<T> reverseIterable(final List<T> list) {
        return iterable(reverseIterator(list));
    }

    /**
     * Creates an Iterable instance that just returns the given Iterator from its iterator() method.
     * 
     * This is useful for using an iterator in a foreach loop directly.
     * 
     * <p>
     * Example use:
     * <pre>
     *     for (Object o : iterable(iterator)) { ... }
     * </pre>
     * 
     * @throws NullPointerException if list is {@code null}
     */
    public static <T> Iterable<T> iterable(final Iterator<T> iter) {
        if (iter == null)
            throw new NullPointerException("iter parameter is null"); //$NON-NLS-1$

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

    /**
     * Returns an iterator that iterates backwards over the given list.
     * The remove() method is not implemented and will throw UnsupportedOperationException.
     * The returned iterator does not support the remove() method.
     * 
     * @throws NullPointerException if list is {@code null}
     */
    public static <T> Iterator<T> reverseIterator(final List<T> list) {
        return new Iterator<T>() {
            ListIterator<T> iterator = list.listIterator(list.size());

            @Override
            public boolean hasNext() {
                return iterator.hasPrevious();
            }

            @Override
            public T next() {
                return iterator.previous();
            }

            @Override
            public void remove() {
                throw new UnsupportedOperationException("remove() not supported"); //$NON-NLS-1$
            }
        };
    }
}