Java Random Element randomElement(E[] array)

Here you can find the source of randomElement(E[] array)

Description

random Element

License

Open Source License

Declaration

public static <E> E randomElement(E[] array) 

Method Source Code

//package com.java2s;
/*//  w w w  .  ja  va 2s .com
 *
 *  * Copyright 2014 Red Hat, Inc.
 *  *
 *  * All rights reserved. This program and the accompanying materials
 *  * are made available under the terms of the Eclipse Public License v1.0
 *  * and Apache License v2.0 which accompanies this distribution.
 *  *
 *  *     The Eclipse Public License is available at
 *  *     http://www.eclipse.org/legal/epl-v10.html
 *  *
 *  *     The Apache License v2.0 is available at
 *  *     http://www.opensource.org/licenses/apache2.0.php
 *  *
 *  * You may elect to redistribute this code under either of these licenses.
 *  *
 *
 */

import java.util.Random;

public class Main {
    private static Random random = new Random();

    public static <E> E randomElement(E[] array) {
        return array[randomPositiveInt() % array.length];
    }

    /**
     * @return a random positive int
     */
    public static int randomPositiveInt() {
        while (true) {
            int rand = random.nextInt();
            if (rand > 0) {
                return rand;
            }
        }
    }
}

Related

  1. randomEle(List list)
  2. randomElem(Random rand, Set partitions)
  3. randomElement(Collection coll)
  4. randomElement(final Set set)
  5. randomElement(int[] anArray)
  6. randomElement(List list)
  7. randomElement(T... values)