Java tutorial
//package com.java2s; /* * File: CollectionUtil.java * Authors: Justin Basilico * Company: Sandia National Laboratories * Project: Cognitive Foundry * * Copyright March 25, 2008, Sandia Corporation. * Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive * license for use of this work by or on behalf of the U.S. Government. Export * of this program may require a license from the United States Government. * See CopyrightHistory.txt for complete details. * */ import java.util.List; public class Main { /** * Returns the indexed value into the {@code Iterable}. It first checks to * see if the {@code Iterable} is a {@code List}, and if so calls the get * method. Otherwise, it walks the {@code Iterable} to get to the element. * * @param <DataType> * The type of data. * @param iterable * The iterable to pull the value from. * @param index * The 0-based index to pull from the iterable. * @return * The value at the given spot in the iterable. * @throws IndexOutOfBoundsException * If the index is less than zero or greater than or equal to the * number of elements in the iterable. */ public static <DataType> DataType getElement(final Iterable<DataType> iterable, int index) { if (iterable instanceof List<?>) { return ((List<DataType>) iterable).get(index); } else { if (index < 0) { // Bad index. throw new IndexOutOfBoundsException("index must be >= 0"); } for (DataType v : iterable) { if (index == 0) { return v; } index--; } // Bad index. throw new IndexOutOfBoundsException("index >= iterable size"); } } }