Get a random position(object) from an array of generic objects. - Android java.lang

Android examples for java.lang:array

Description

Get a random position(object) from an array of generic objects.

Demo Code


import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

public class Main{
    /**/* w ww . java  2  s . c o  m*/
     * Get a random position(object) from an array of generic objects. <br/>
     * Using generics saves the trouble of casting the return object.
     * 
     * @param <T> -the type of the array to get the object from.
     * @param array -the array with objects.
     * @return random object from given array or null of array is either null or empty.
     */
    public static <T> T getRandomPosition(T[] array) {
        if (array == null || array.length == 0) {
            return null;
        }
        return array[MathUtils.getRandomInteger(array.length - 1)];
    }
    /**
     * Get a random position(object) from a list of generic objects. <br/>
     * Using generics saves the trouble of casting the return object.
     * 
     * @param <T> -the type of the list objects to get the object from.
     * @param {{@link {@link List}} -the list with objects.
     * @return random object from given list or null of list is either null or empty.
     */
    public static <T> T getRandomPosition(List<T> list) {
        if (list == null || list.isEmpty()) {
            return null;
        }
        return list.get(MathUtils.getRandomInteger(list.size() - 1));
    }
    /**
     * Returns true if list is null or its size is 0
     * 
     * <pre>
     * isEmpty(null)   =   true;
     * isEmpty({})     =   true;
     * isEmpty({1})    =   false;
     * </pre>
     * 
     * @param <V>
     * @param list - of {@link List} type.
     * @return boolean - true if list is null or empty, else false.
     */
    public static <V> boolean isEmpty(List<V> list) {
        return (list == null || list.size() == 0);
    }
}

Related Tutorials