例題1:產生10個1~20之間的隨機數,要求隨機數不能重復
import java.util.HashSet;
import java.util.Random;
public class Test1 {/*** 產生10個1~20之間的隨機數,要求隨機數不能重復* * 分析:* 1,有Random類創建隨機數對象* 2,需要儲存10個隨機數,而且不能重復,所以我們用HashSet集合* 3,如果HashSetsize是小于10就可以不斷的存儲,如果大于等于10就停止儲存* 4,通過Random類中的nextInt(n)方法獲取1到20之間的隨機數,并將這些隨機數存儲在HashSet集合中* 5,遍歷HashSet* */public static void main(String[] args) {//1,有Random類創建隨機數對象Random wsq = new Random(); //2,需要存儲10個隨機數,而且不能重復,所以我們用HashSet集合HashSet<Integer> yy = new HashSet<>();//3,如果HashSetsize是小于10就可以不斷的存儲,如果大于等于10就停止儲存while(yy.size()<10){//4,通過Random類中的nextInt(n)方法獲取1到20之間的隨機數,并將這些隨機數存儲在HashSet集合中yy.add(wsq.nextInt(20));}for (Integer integer : yy) {System.out.println(integer);} }
}
例題2:使用Scanner從鍵盤讀取一行輸入,去掉其中重復字符,打印出不同的那些字符
import java.util.HashSet;
import java.util.Scanner;
public class Test2 {
/*** 使用Scanner從鍵盤讀取一行輸入,去掉其中重復字符,打印出不同的那些字符* aaaabbbcccddd* bcda* * 分析:* 1,創建Scanner對象* 2,創建HashSet對象,將字符存儲,去掉重復* 3,將字符串轉換為字符數組,獲取每一個字符存儲在HashSet集合中,自動去除重復* 4,遍歷HashSet,打印每一個字符* * */public static void main(String[] args) {//1,創建Scanner對象Scanner wsq = new Scanner(System.in);System.out.println("請輸入一行字符串:");//2,創建HashSet對象,將字符存儲,去掉重復HashSet<Character> yy = new HashSet<>();//3,將字符串轉換為字符數組,獲取每一個字符存儲在HashSet集合中,自動去除重String line = wsq.nextLine();char [] arr = line.toCharArray();for (Character c : arr) {yy.add(c);}//4,遍歷HashSet,打印每一個字符for(Character ch : yy){System.out.print(ch);}}
}
例題3:將集合中的重復元素去掉
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
public class Test3 {/*** 要求:將集合中的重復元素去掉* * * 分析:* 1,創建一個List集合存儲若干個重復元素* 2,單獨定義方法去除重復* 3,打印一下List集合* * */public static void main(String[] args) {//1,創建一個List集合存儲若干個重復元素ArrayList<String> list = new ArrayList<>();list.add("a");list.add("b");list.add("b");list.add("b");list.add("b");list.add("b");list.add("c");list.add("c");list.add("c");list.add("c");list.add("c");list.add("c");list.add("d");list.add("d");list.add("d");list.add("d");list.add("d");list.add("d");//2,單獨定義方法去除重復getSingle(list); //獲取單個元素//3,打印一下List集合System.out.println(list);}/*** 分析:* 去除List集合在的重復元素* 1,創建一個LinkedHashSet集合* 2,將List集合中所以的元素添加到LinkedHashSet集合中* 3,將List集合中的元素清除* 4,將LinkedHashSet集合中元素添加到List集合中* */private static void getSingle(List<String> list) {//1,創建一個LinkedHashSet集合LinkedHashSet<String> lhs = new LinkedHashSet<>();//2,將List集合中所以的元素添加到LinkedHashSet集合中lhs.addAll(list);//3,將List集合中的元素清除list.clear();//4,將LinkedHashSet集合中元素添加到List集合中list.addAll(lhs);}
}