Returns the index-th value in object, throwing IndexOutOfBoundsException if there is no such element or IllegalArgumentException if object is not an instance of one of the supported types. - Java java.util

Java examples for java.util:Arrays

Description

Returns the index-th value in object, throwing IndexOutOfBoundsException if there is no such element or IllegalArgumentException if object is not an instance of one of the supported types.

Demo Code


//package com.java2s;
import java.lang.reflect.Array;

import java.util.Collection;

import java.util.Enumeration;

import java.util.Iterator;

import java.util.List;
import java.util.Map;

public class Main {
    public static void main(String[] argv) {
        Object object = "java2s.com";
        int index = 42;
        System.out.println(get(object, index));
    }/*w  w w.  ja va2s.  co  m*/


    public static Object get(Object object, int index) {
        if (index < 0) {
            throw new IndexOutOfBoundsException(
                    "Index cannot be negative: " + index);
        }
        if (object instanceof Map) {
            Map<?, ?> map = (Map<?, ?>) object;
            Iterator<?> iterator = map.entrySet().iterator();
            return get(iterator, index);
        } else if (object instanceof List) {
            return ((List<?>) object).get(index);
        } else if (object instanceof Object[]) {
            return ((Object[]) object)[index];
        } else if (object instanceof Iterator) {
            Iterator<?> it = (Iterator<?>) object;
            while (it.hasNext()) {
                index--;
                if (index == -1) {
                    return it.next();
                } else {
                    it.next();
                }
            }
            throw new IndexOutOfBoundsException("Entry does not exist: "
                    + index);
        } else if (object instanceof Collection) {
            Iterator<?> iterator = ((Collection<?>) object).iterator();
            return get(iterator, index);
        } else if (object instanceof Enumeration) {
            Enumeration<?> it = (Enumeration<?>) object;
            while (it.hasMoreElements()) {
                index--;
                if (index == -1) {
                    return it.nextElement();
                } else {
                    it.nextElement();
                }
            }
            throw new IndexOutOfBoundsException("Entry does not exist: "
                    + index);
        } else if (object == null) {
            throw new IllegalArgumentException(
                    "Unsupported object type: null");
        } else {
            try {
                return Array.get(object, index);
            } catch (IllegalArgumentException ex) {
                throw new IllegalArgumentException(
                        "Unsupported object type: "
                                + object.getClass().getName());
            }
        }
    }
}

Related Tutorials