get Element from List by index, null safe - Android java.util

Android examples for java.util:List Element

Description

get Element from List by index, null safe

Demo Code


//package com.book2s;

import java.util.Collection;

import java.util.List;

import java.util.Map;

public class Main {
    public static void main(String[] argv) {
        List list = java.util.Arrays.asList("asdf", "book2s.com");
        int index = 42;
        System.out.println(getElement(list, index));
    }/*from w w w.j av  a  2s  . co m*/

    public static <T> T getElement(List<T> list, int index) {
        if (isEmpty(list)) {
            return null;
        }
        if (index < 0 || index >= list.size()) {
            return null;
        }
        return list.get(index);
    }

    public static <T> T getElement(T[] array, int index) {
        if (isEmpty(array)) {
            return null;
        }
        if (index < 0 || index >= array.length) {
            return null;
        }
        return array[index];
    }

    public static boolean isEmpty(Collection<?> c) {
        return c == null || c.isEmpty();
    }

    public static boolean isEmpty(Map<?, ?> map) {
        return map == null || map.isEmpty();
    }

    @SafeVarargs
    public static <T> boolean isEmpty(T... array) {
        return array == null || array.length == 0;
    }
}

Related Tutorials