zoukankan      html  css  js  c++  java
  • LinkedHashSet 和 不重复随机数

    1.LinkedHashSet 的概述和使用

      llinkedHashSet 的特点: 是唯一能保证怎么存就怎么输出的 set 集合,并且去重复

     1 LinkedHashSet<String> linkSet = new LinkedHashSet<>();
     2         /* LinkedHashSet可以保证元素唯一,并且可以保证有序(怎么存,就怎么取) */
     3         linkSet.add("f");
     4         linkSet.add("a");
     5         linkSet.add("b");
     6         linkSet.add("c");
     7         linkSet.add("c");
     8         linkSet.add("d");
     9         linkSet.add("e");
    10         // 增强for循环遍历LinkedHashSet
    11         for (String s : linkSet) {
    12             System.out.print(s + " ");
    13         }
           //输出结果为:f a b c d e

    2.产生10个1~20个随机数,要求不能重复

    1   HashSet<Integer> hs = new HashSet<>();    //创建集合对象
    2         Random r = new Random();               //创建随机数对象
    3         while(hs.size() < 10) {
    4             int num = r.nextInt(20) + 1;         //生成1到20的随机数
    5             hs.add(num);
    6         }
    7         for (Integer integer : hs) {            //遍历集合
    8             System.out.println(integer);         //打印每一个元素
    9         }

     

    3.用Scanner方法从键盘读取一行输入,去除其中重复的字符,打印出不同的那些字符

      

     1     /*
     2          * 1.创建键盘录入对象,
     3          *  2.创建一个hashset对象保存键盘录入的字符 
     4          *  3.遍历字符,并存进hashset对象
     5          */
     6 
     7         Scanner sc = new Scanner(System.in);
     8         System.out.println("请输入要去重复的字符");
     9         String str = sc.next();
    10         // 创建hashset对象
    11         HashSet<Character> hash = new HashSet<>();
    12         // 把字符串转换成字符数组
    13         char[] ch = str.toCharArray();
    14         for (int i = 0; i < ch.length; i++) {
    15             char c = ch[i];
    16             hash.add(c);
    17         }
    18         System.out.println(hash);

      

  • 相关阅读:
    【PyQt5-Qt Designer】QSpinBox-微调框
    【PyQt5-Qt Designer】QProgressBar() 进度条
    【PyQt5-Qt Designer】QSlider滑块
    Tomcat eclipse 启动时一个工程影响另一个工程
    apache thrift 和 apache jersey 记录
    常用 Linux 命令
    mac 命令记录
    eclipse m2eclipse 从Maven的本地库中读取依赖库
    成功build Maven但eclipse中依然显示该工程有错误
    mac install: /usr/bin/unrar: Operation not permitted
  • 原文地址:https://www.cnblogs.com/xsh726/p/11378922.html
Copyright © 2011-2022 走看看