容器-单例集合使用案例(十四)
-
需求:产生1-10之间的随机数([1,10]并区间),将重复的10个随机数放到容器中。
-
使用List类型容器实现
import java.util.ArrayList; import java.util.List; public class ListDemo { public static void main(String[] args) { List<Integer> list=new ArrayList<>(); while (true){//我们不知道要循环几次,因为是随机的,干脆就给了个死循环 //产生随机数 int num = (int) (Math.random() * 10 + 1); //判断当前元素i容器中是否存在 if (!list.contains(num)){ list.add(num); } //结束循环 if (list.size()==10){ break; } } //遍历list集合中的元素 for (Integer i:list){ System.out.println(i); } } }
-
使用Set类型容器类实现
import java.util.HashSet; import java.util.Set; public class SetDemo { public static void main(String[] args) { Set<Integer> set=new HashSet<>(); while (true){ int num=(int)(Math.random()*10+1); //将元素添加容器中,由于Set类型容器是不允许有重复元素的,所以不需要判断 set.add(num); //结束循环 if (set.size()==10){ break; } } for (Integer i:set){ System.out.println(i); } } }
-
Set类型容器类实现,存在一些问题,打印出来的数字是有序的,而HashSet是没有排序的,只有TreeSet才是有排序的,但是结果为什么会是有序的呢。答:这个是假有序的,我们去分析HashCode就会知道。
-
先进入Integer的源码,用Ctrl+F快捷键搜索hashCode的方法
/** * Returns a hash code for a {@code int} value; compatible with * {@code Integer.hashCode()}. * * @param value the value to hash * @since 1.8 * * @return a hash code value for a {@code int} value. */ public static int hashCode(int value) { return value;//我们可以看到hashCode是返回一个int类型的Value值 }
-
从Hash算法的原理去分析,
-