标签:
import java.util.*; public class RandomNum { public static void main(String[] args) { /*HashSet去重后重新洗牌;而LinkedHashSet去重后并不打乱放入顺序*/ HashSet<String> list = new HashSet<String>(); list.add("Apple"); list.add("Boy"); list.add("Cat"); list.add("Dog"); list.add("Elephant"); list.add("Dog"); list.add("Elephant"); System.out.println(list.toString()); System.out.println(getRandomNum(new ArrayList(list),3)); } /** * 返回随机数 * @param list 备选号码 * @param selected 备选数量 * @return */ public static List<String> getRandomNum(List<String> list, int selected) { List<String> reList = new ArrayList<String>(); Random random = new Random(); // 先抽取,备选数量的个数 if (list.size() >= selected) { for (int i = 0; i < selected; i++) { // 随机数的范围为0-list.size()-1; int target = random.nextInt(list.size()); reList.add(list.get(target)); list.remove(target); } } else { selected = list.size(); for (int i = 0; i < selected; i++) { // 随机数的范围为0-list.size()-1; int target = random.nextInt(list.size()); reList.add(list.get(target)); list.remove(target); } } return reList; } }
标签:
原文地址:http://my.oschina.net/yunsy/blog/507548