HashSet和LinkedHashSet练习

来源:互联网 发布:openstack 源码分析 编辑:程序博客网 时间:2024/06/01 08:26

编写一个程序,获取10个1至20的随机数,要求随机数不能重复。并把最终的随机数输出到控制台

import java.util.HashSet;import java.util.Random;public class a {/** * 需求:编写一个程序,获取10个1至20的随机数,要求随机数不能重复。并把最终的随机数输出到控制台。 */public static void main(String[] args) {//1,有Random类创建随机数对象Random r = new Random();//2,需要存储10个随机数,而且不能重复,所以我们用HashSet集合HashSet<Integer> hs = new HashSet<>();//3,如果HashSet的size是小于10就可以不断的存储,如果大于等于10就停止存储while(hs.size() < 10) {//4,通过Random类中的nextInt(n)方法获取1到20之间的随机数,并将这些随机数存储在HashSet集合中hs.add(r.nextInt(20) + 1);}// 5,遍历HashSetfor (Integer integer : hs) {System.out.println(integer);}}}

使用Scanner从键盘读取一行输入,去掉其中重复字符, 打印出不同的那些字符

import java.util.HashSet;import java.util.Scanner;public class b {/** * * 使用Scanner从键盘读取一行输入,去掉其中重复字符, 打印出不同的那些字符 */public static void main(String[] args) {//1,创建Scanner对象Scanner sc = new Scanner(System.in);System.out.println("请输入一行字符串:");//2,创建HashSet对象,将字符存储,去掉重复HashSet<Character> hs = new HashSet<>();//3,将字符串转换为字符数组,获取每一个字符存储在HashSet集合中,自动去除重复String line = sc.nextLine();char[] arr = line.toCharArray();for (char c : arr) {//遍历字符数组hs.add(c);}//4,遍历HashSet,打印每一个字符for(Character ch : hs) {System.out.print(ch);}}}

将集合中的重复元素去掉

import java.util.ArrayList;import java.util.LinkedHashSet;import java.util.List;public class c {/** *  需求:将集合中的重复元素去掉 */public static void main(String[] args) {//1,创建List集合存储若干个重复元素ArrayList<String> list = new ArrayList<>();list.add("a");list.add("a");list.add("a");list.add("b");list.add("b");list.add("b");list.add("c");list.add("c");list.add("c");list.add("c");//2,单独定义方法去除重复getSingle(list);//3,打印一下List集合System.out.println(list);}/* * 分析 * 去除List集合中的重复元素 * 1,创建一个LinkedHashSet集合 * 2,将List集合中所有的元素添加到LinkedHashSet集合 * 3,将list集合中的元素清除 * 4,将LinkedHashSet集合中的元素添加回List集合中 */public 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);}}





0 0