Java学习-HashSet练习

创建一个长度是200的字符串数组
使用长度是2的随机字符填充该字符串数组
统计这个字符串数组里重复的字符串有多少种
使用HashSet来解决这个问题

 1 package Collection;
 2 
 3 import java.util.HashSet;
 4 
 5 public class HashSetTest {
 6     public static char randChar() { // 创建随机字符
 7         while (true) {
 8             char c = (char) (Math.round(Math.random() * 126));
 9             if (Character.isDigit(c) || Character.isLetter(c)) {
10                 return c;
11             }
12         }
13     }
14 
15     public static void print(String arr[]) { // 控制打印输出
16         for (int i = 0; i < arr.length; i++) {
17             if ((i + 1) % 20 == 0) {
18                 System.out.printf(arr[i] + "\n");
19             } else {
20                 System.out.printf(arr[i] + "\t");
21             }
22         }
23     }
24 
25     public static void main(String[] args) {
26         // 创建随机字符串数组
27         String arr[] = new String[200];
28         for (int i = 0; i < arr.length; i++) {
29             arr[i] = "" + randChar() + randChar();
30         }
31         print(arr); // 格式化打印输出
32         HashSet<String> set = new HashSet<>(); // 用来判断哪些是重复字符串
33         HashSet<String> res = new HashSet<>(); // 用来保存重复的字符串
34         for (String s : arr) {
35             if (set.add(s) == false)
36                 res.add(s);
37         }
38         System.out.printf("一共有%d种重复字符串", res.size());
39         System.out.println("分别是:\n" + res);
40     }
41 }

效果图:

猜你喜欢

转载自www.cnblogs.com/gilgamesh-hjb/p/12221204.html