A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 汪洪吉 初级黑马   /  2019-4-19 08:07  /  490 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

public class Work {
//程序主方法入口
    public static void main(String[] args) {
//创建hashset集合
        HashSet<Integer> hashset = new HashSet<>();
//创建产生随机数的方法
        Random ran = new Random();
//进入循环,当hashset集合长度为10停下
        while (hashset.size()<10){
//产生一个0到9的数
            int i = ran.nextInt(10);
//添加的集合中,重复数字不添加
            hashset.add(i);
        }
//输出集合内容
        System.out.println(hashset);
    }
}
程序结果为:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
public class Work {
    public static void main(String[] args) {
        HashSet<Integer> hashset = new HashSet<>();
        Random ran = new Random();
        while (hashset.size()<10){
            int i = ran.nextInt();//产生一个随机int数
            hashset.add(i);
        }
        System.out.println(hashset);
    }
}
程序结果为:[-785008203, -1034755822, 764424403, 1056402898, 1389045516,
-37467091, -38450971,-2013549591,-1283523704, -2063251469]
public class Work {
    public static void main(String[] args) {
        HashSet<Integer> hashset = new HashSet<>();
        Random ran = new Random();
        while (hashset.size()<10){
            int i = ran.nextInt(40);
            hashset.add(i);
        }
        System.out.println(hashset);
//创建一个hashset集合长度的数组用以验证
        int[] arr = new int[hashset.size()];
        int a = 0;
        for (Integer integer : hashset) {
            int i = integer%16;
//把hashset集合中的没一个元素取模底层数组长度,得到一个数组
            arr[a]=i;
            a++;
        }
        arrays(arr);//调用方法输出数组元素
    }
    public static void arrays(int[] arr){
        System.out.print("[");
        for (int i = 0; i < arr.length; i++) {
            if (i==arr.length-1){
                System.out.print(arr[i]);
            }else{
                System.out.print(arr[i]+", ");
            }
        }
        System.out.println("]");
    }
}
程序结果:[17, 2, 20, 22, 26, 11, 28, 29, 14, 15]
         [1, 2, 4, 6, 10, 11, 12, 13, 14, 15]
hashset集合的底层是通过数组加链表来形成的,通过哈希值来确保元素的唯一性,而integer的哈希值就是它本身
       public static int hashCode(int value) {
               return value;
           }
//上面为Integer的hashcode源码,返回值为本身
           当我们把得到的哈希值模于hasheset底层数组长度时它所对应的自然升序就是我们hashset的顺序

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马