Here you can find the source of random(Collection> collection)
Parameter | Description |
---|---|
collection | a parameter |
public static Object random(Collection<?> collection)
//package com.java2s; //License from project: Open Source License import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Random; public class Main { /**/*from w w w . j a v a 2 s . co m*/ * Ritorna un oggetto random della collezione. * * @param collection * @return */ public static Object random(Collection<?> collection) { int index = new Random().nextInt(collection.size()); if (collection instanceof List<?>) return ((List<?>) collection).get(index); Iterator<?> it = collection.iterator(); Object result = null; for (int i = 0; it.hasNext() && i <= index; i++) // esce con i==index result = it.next(); return result; } public static int size(Collection<?> collection) { return isEmpty(collection) ? 0 : collection.size(); } /** * Test se la collection IS EMPTY * * @param collection * @return */ public static boolean isEmpty(Collection<?> collection) { return collection == null || collection.isEmpty(); } public static boolean isEmpty(Object[] array) { return array == null || array.length == 0; } public static boolean isEmpty(Map<?, ?> map) { return map == null || map.isEmpty(); } }