package demo; import java.util.HashSet; import java.util.Random; public class RandomDemo { public static void main(String[] args) { HashSet<Integer> hashSet = new HashSet(); randomSet(hashSet); System.out.println(hashSet); } private static void randomSet(HashSet<Integer> hashSet) { if (hashSet.size() == 10) { //如果hashSet等于10,不需要递归 return; } Random random = new Random(); for (int i = 0; i < 10 - hashSet.size(); i++) { hashSet.add(random.nextInt(20) + 1); } if (hashSet.size() < 10) {// 如果hashSet不足10个,递归 randomSet(hashSet); } } }