前言
上次用数组和List实现了双色球案例, 今天复习了Set, 就利用Set写一个吧:
一、Set简介:
Set 集合是 Collection 的子类接口,与 List 类似,都需要通过自己的实现类来进行操作
Set 集合的特点
不可以包含重复的值
没有带索引的方法,不能使用普通到的 for 循环对其进行遍历
不保证读写顺序
二、代码实现
1.利用HashSet实现乱序红球
代码如下:
import java.util.HashSet;
import java.util.Set;
public class Demo03 {
public static void main(String[] args) {
Random ran = new Random();
// 无序的 Set 集合 - 不保证读写顺序
// HashSet<Integer> redBalls = new HashSet<>();
// 有序的 Set 集合 - 带有逻辑顺序的 Set 集合
HashSet<Integer> redBalls = new HashSet<>();
int blueBall = ran.nextInt(16) + 1;
int count = 0;
// 处理红球
while (redBalls.size() < 6) {
redBalls.add(ran.nextInt(33) + 1);
count++;
}
// 输出结果
System.out.println("红球:" + redBalls + " | 蓝球:" + blueBall);
System.out.println("一共生成了" + count + "次红球!~");
}
}
2.利用TreeSet实现乱正序红球
TreeSet是SortedSet接口的唯一实现类,TreeSet可以确保集合元素处于排序状态。
可以进行定制排序 和 自然排序,这里不做简介.
代码如下:
import java.util.HashSet;
import java.util.Random;
import java.util.TreeSet;
public class Demo03 {
public static void main(String[] args) {
Random ran = new Random();
// 无序的 Set 集合 - 不保证读写顺序
// HashSet<Integer> redBalls = new HashSet<>();
// 有序的 Set 集合 - 带有逻辑顺序的 Set 集合
TreeSet<Integer> redBalls = new TreeSet<>();
int blueBall = ran.nextInt(16) + 1;
int count = 0;
// 处理红球
while (redBalls.size() < 6) {
redBalls.add(ran.nextInt(33) + 1);
count++;
}
// 输出结果
System.out.println("红球:" + redBalls + " | 蓝球:" + blueBall);
System.out.println("一共生成了" + count + "次红球!~");
}
}