get Element from Collection At Index - Android java.util

Android examples for java.util:Collection Find

Description

get Element from Collection At Index

Demo Code


//package com.book2s;
import java.util.Collection;
import java.util.Iterator;

public class Main {
    public static void main(String[] argv) {
        Collection set = java.util.Arrays.asList("asdf", "book2s.com");
        int idx = 42;
        System.out.println(getElementAtIndex(set, idx));
    }/* w  w w .  jav  a2 s.c  o  m*/

    public static <E> E getElementAtIndex(Collection<E> set, int idx) {
        if (idx >= set.size() || idx < 0) {
            throw new IndexOutOfBoundsException();
        }
        Iterator<E> it = set.iterator();
        for (int i = 0; i < idx; ++i) {
            it.next();
        }
        return it.next();
    }
}

Related Tutorials