Java Random Enum randomEnumSet(Class enumType)

Here you can find the source of randomEnumSet(Class enumType)

Description

random Enum Set

License

Open Source License

Declaration

public static <E extends Enum<E>> Set<E> randomEnumSet(Class<E> enumType) 

Method Source Code

//package com.java2s;
/*// w  w w.  j  a  v a  2 s.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.EnumSet;
import java.util.Random;
import java.util.Set;

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

    public static <E extends Enum<E>> Set<E> randomEnumSet(Class<E> enumType) {
        EnumSet<E> set = EnumSet.noneOf(enumType);
        for (E e : EnumSet.allOf(enumType)) {
            if (randomPositiveInt() % 2 == 1) {
                set.add(e);
            }
        }
        return set;
    }

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

Related

  1. RandomEnum(Class c)
  2. randomEnum(Class c)
  3. randomEnum(Class clazz)
  4. randomEnum(Class cls, T exceptValue)