Java Iterable Item getFrom(Iterable iterable, int index)

Here you can find the source of getFrom(Iterable iterable, int index)

Description

get From

License

Apache License

Declaration

@SuppressWarnings("unchecked")
    public static <T> T getFrom(Iterable<T> iterable, int index) throws IndexOutOfBoundsException 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.util.Collection;
import java.util.List;

public class Main {
    @SuppressWarnings("unchecked")
    public static <T> T getFrom(Iterable<T> iterable, int index) throws IndexOutOfBoundsException {
        //could throw IndexOutOfBoundsException
        if (iterable instanceof List<?>) {
            return (T) ((List<?>) iterable).get(index);
        }//from  w w  w.  j  a va  2  s . co m

        return elementAt(iterable, index);
    }

    public static <T> T elementAt(Iterable<T> iterable, int index) {
        checkIndex(iterable, index);

        int currIndex = 0;
        T out = null;

        for (T obj : iterable) {
            if (currIndex == index) {
                out = obj;
                break;
            }
            ++currIndex;
        }

        return out;
    }

    public static <T> void checkIndex(Iterable<T> iterable, int index) {
        if (index > sizeOf(iterable) - 1 || index < 0) {
            throw new IndexOutOfBoundsException("Index " + index + " is out of the bounds of " + iterable);
        }
    }

    public static int sizeOf(Iterable<?> iterable) {
        if (iterable instanceof Collection<?>) {
            return ((Collection<?>) iterable).size();
        }

        int size = 0;
        for (@SuppressWarnings("unused")
        Object o : iterable) {
            ++size;
        }
        return size;
    }
}

Related

  1. concat(Iterable first, Iterable second)
  2. contains(Iterable iter, Object o)
  3. getFirst(final Iterable iterable)
  4. getFirst(Iterable iterable)
  5. getFirstElement(Object maybeIterable)
  6. isIterable(Object obj)
  7. isPrefix(Iterable suspectedPrefix, Iterable container)
  8. iterableContains(Iterable i, E match)
  9. maxes(Iterable elements)