Java中set集合

Set集合

set集合简单使用

package com.cloud.vector;

import java.util.HashSet;

import java.util.Set;

public class Day2 {

/*

 --|Set 实现Set接口的集合类,无序,不可以重复

        元素添加输出的顺序不一样

*/

   public static void main(String[] args) {

      Set set=new HashSet();

      set.add("Spring1");

      set.add("Spring2");

      set.add("Spring3");

      System.out.println("添加是否成功?"+set.add("Spring3"));

      System.out.println(set);

   }

}

Set集合添加元素

package com.cloud.vector;

import java.util.HashSet;

public class Day3 {

   public static void main(String[] args) {

      HashSet<Person> set=new HashSet<Person>();

      /* 添加简单元素,该元素不可重复

      set.add("Spring1");

      set.add("Spring2");

      set.add("Spring3");

      set.add("Spring3");

      */

      set.add(new Person(1,"Spring1"));

      set.add(new Person(2,"Spring2"));

      set.add(new Person(3,"Spring3"));

      System.out.println("是否添加成功?"+set.add(new Person(3,"Spring3")));

      System.out.println(set);

   }

}

class Person{

   int id;

   String name;

   public Person(int id,String name){

      this.id=id;

      this.name=name;

   }

   @Override

   public String toString() {

      return "{编号="+this.id+";名字="+this.name+"}";

   }

   @Override

   public boolean equals(Object obj) {

      System.out.println("equals(Object obj)被调用");

      Person p=(Person) obj;

      return this.id==p.id;

   }

   @Override

   public int hashCode() {

      System.out.println("===调用了hashCode()===");

      //这里修改返回id

      return this.id;

   }

}

String类型的比较

package com.cloud.vector;

public class Demo4 {

   public static void main(String[] args) {

      String str1="hello";

      String str2=new String("hello");

      System.out.println("判断两个是否是相同的对象:"+(str1==str2));

      //hashCode默认情况下表示的是内存地址,但是String重写的了objecthashCode()的方法

      System.out.println("hashCode="+str1.hashCode());

      System.out.println("hashCode="+str2.hashCode());

   }

}

HashSet简单使用

package com.cloud.vector;

import java.util.HashSet;

import java.util.Scanner;

public class Demo5 {

   /**

    * 实现的需求:键盘录入用户名和密码,如果用户名和密码已经存在,则重复阻止添加

    */

   public static void main(String[] args) {

      @SuppressWarnings("resource")

      Scanner scanner = new Scanner(System.in);

      HashSet<User> set=new HashSet<User>();

      while(true){

        System.out.println("请输入用户名:");

        String userName = scanner.next();

        System.out.println("请输入密码:");

        String password = scanner.next();

        //创建用户

        User user = new User(userName,password);

        if(set.add(user)){

           System.out.println("注册成功...");

           System.out.println("用户信息:"+set);

        }

        else{

           System.out.println("注册失败...");

        }

      }

   }

}

class User{

   String userName;

   String password;

   public User(String userName,String password){

      super();

      this.userName=userName;

      this.password=password;

   }

   @Override

   public String toString() {

      return "{用户名:"+this.userName+";密码:"+this.password;

   }

   @Override

   public boolean equals(Object obj) {

      User user = (User)obj;

      return this.userName.equals(user.userName)&&this.password.equals(user.password);

   }

   @Override

   public int hashCode() {

      return userName.hashCode()+password.hashCode();

   }

}

 

TreeSet简单用法

package com.cloud.vector;

import java.util.TreeSet;

public class Demo7 {

   public static void main(String[] args) {

      TreeSet tree = new TreeSet();

      /*tree.add(4);

      tree.add(3);

      tree.add(6);

      tree.add(5);

      tree.add(2);

      //打印:[2, 3, 4, 5, 6]

      */

      tree.add('c');

      tree.add('e');

      tree.add('b');

      tree.add('a');

      //打印:[a, b, c, e]

      System.out.println(tree);

   }

}

 

TreeSet添加自定义元素

package com.cloud.vector;

import java.util.TreeSet;

public class Demo8 {

   /**

    * TreeSet处理自定义成员变量

    * 注意事项:

    * 1.如果元素具备自然特性,则按照元素的自然特性进行排序

    * 2.如果元素不具备自然顺序的特性,那么元素所属的类必须实现Comparable接口

    * 3.如果compareTo方法返回的是0,那么该元素视为重复元素,不允许添加

    * 4.在添加元素中,如果该元素不具备自然特性,该元素所属的类也没有实现Comparable接口,就必须

    *   在创建TreeSet的时候传入一个比较器,把元素的比较放到compare方法中即可

    *    比较器使用方法:

    *    class 类名 implements Comparator{

    *    }

    * 5.在传入元素的时候,如果元素本身不具备自然特性,但是元素所属的类实现了Comparable接口,同时

    *   TreeSet对象也传入了比较器,则比较器的规则优先使用

    * 6.TreeSet可以对字符串进行比较

    *    情况1:可以找到对应不同的字符,比较的就是对应的字符

    *

    *    情况2:找不到对应的不同的字符,比较的就是字符串长度

    */

   public static void main(String[] args) {

      TreeSet<Employee> tree = new TreeSet<Employee>();

      tree.add(new Employee(1, "aaa", 500));

      tree.add(new Employee(2, "bbb", 400));

      tree.add(new Employee(3, "ccc", 300));

      tree.add(new Employee(4, "ddd", 200));

      //打印薪水由低到高排序

      System.out.println(tree);

   }

}

@SuppressWarnings("rawtypes")

class Employee implements Comparable{

   int id;

   String name;

   int salary;

   public Employee(int id, String name, int salary) {

      super();

      this.id = id;

      this.name = name;

      this.salary = salary;

   }

   @Override

   public String toString() {

      return "{编号:"+this.id+";姓名:"+this.name+";薪水:"+this.salary+"}";

   }

   //该方法定义元素之间的比较规则

   //比较此对象(this)与制定对象的顺序

   @Override

   public int compareTo(Object o) {

      Employee emp=(Employee) o;

      System.out.println(this.name+""+emp.name+"比较");

      return this.salary-emp.salary;

   }

}

 

TreeSet中比较器的使用

package com.cloud.vector;

import java.util.Comparator;

import java.util.TreeSet;

public class Demo9 {

   /**

    * 比较器使用的案例

    *   比较器使用方法:

    *    class 类名 implements Comparator{

    *    }

    */

   public static void main(String[] args) {

      //创建一个比较器

      MyComparator mycom = new MyComparator();

      //把比较器传入

      TreeSet<Employee2> tree = new TreeSet<Employee2>(mycom);

      tree.add(new Employee2(1, "aaa", 500));

      tree.add(new Employee2(2, "bbb", 400));

      tree.add(new Employee2(3, "ccc", 300));

      tree.add(new Employee2(4, "ddd", 200));

      System.out.println(tree);

   }

}

@SuppressWarnings("rawtypes")

class Employee2 /*implements Comparable*/{

   int id;

   String name;

   int salary;

   public Employee2(int id, String name, int salary) {

      super();

      this.id = id;

      this.name = name;

      this.salary = salary;

   }

   @Override

   public String toString() {

      return "{编号:"+this.id+";姓名:"+this.name+";薪水:"+this.salary+"}";

   }

   //该方法定义元素之间的比较规则

   //比较此对象(this)与制定对象的顺序

   /*

   @Override

   public int compareTo(Object o) {

      Employee2 emp=(Employee2) o;

      System.out.println(this.name+""+emp.name+"比较");

      return this.salary-emp.salary;

   }

   */

}

//自定义一个比较器

class MyComparator implements Comparator{

   @Override

   public int compare(Object o1, Object o2) {

      Employee2 emp1=(Employee2) o1;

      Employee2 emp2=(Employee2) o2;

      return emp1.id-emp2.id;

   }

}

 

TreeSet比较字符串

package com.cloud.vector;

import java.util.TreeSet;

public class Demo10 {

   /**

    * TreeSet比较字符串案例

    */

   public static void main(String[] args) {

      TreeSet tree = new TreeSet();

      //abcabw比较的是cwabcabcd比较的是d

      tree.add("abc");

      tree.add("abcd");

      tree.add("abw");

      System.out.println(tree);

      System.out.println("a".compareTo("c"));

   }

}

 

TreeSet案例

package com.cloud.vector;

import java.util.TreeSet;

public class Demo11 {

   /**

    * 对字符串进行排序

    * String ='2 15 17 4 8 6 12'

    */

   public static void main(String[] args) {

      String str="2 15 17 4 8 6 12";

      String[] datas = str.split(" ");

      TreeSet tree = new TreeSet();

      for(int i=0;i<datas.length;i++){

        tree.add(Integer.parseInt(datas[i]));

      }

      System.out.println(tree);

   }

}


<think>好的,用户想要寻找关于JavaSet集合的经典代码示例和练习。我需要先回忆一下Set集合的基本概念和常用实现类,比如HashSet、TreeSet和LinkedHashSet。根据引用内容,用户可能已经了解Set的基本特性,比如不允许重复元素,以及如何通过比较器或自然排序来排序元素。 首先,我应该提供一些基础的代码示例,展示如何创建Set、添加元素、遍历等操作。比如使用HashSet的简单例子,然后引入TreeSet的自然排序和定制排序。引用中提到需要比较器类,所以可能需要演示如何实现Comparator接口。 接下来,用户可能需要更复杂的练习,比如去重、集合运算(交集、并集、差集)或者结合泛型使用。引用中的泛型方法示例可能相关,可以展示如何在Set中使用泛型。 还要考虑实际应用场景,比如统计单词数量,处理学生成绩排名等。这些例子能帮助用户理解Set的实际用途。同时,引用中提到的TreeMap可能需要稍微提及,但重点应放在Set上。 需要确保代码语法正确,符合用户提供的引用中的格式。比如,比较器类的实现,自然排序通过Comparable接口,以及使用Lambda表达式简化代码。此外,用户可能需要了解线程安全的Set,所以可以提到ConcurrentSkipListSet,并给出示例。 最后,生成相关问题,帮助用户进一步学习,比如性能分析、线程安全的选择、比较器与Comparable的区别等。这些问题应基于提供的引用和常见的学习难点。 现在,整理这些思路,分步骤给出示例代码,并确保每个例子都有注释说明,符合用户的要求。同时,引用相关的引用内容,比如比较器类和自然排序的实现,以增强答案的可靠性。</think>以下是一些Java Set集合的经典代码示例和练习,结合了基础操作、应用场景和进阶技巧: ### 一、基础操作示例 1. **HashSet去重** ```java Set<String> cities = new HashSet<>(); Collections.addAll(cities, "北京", "上海", "广州", "北京", "深圳"); System.out.println(cities); // 输出:[北京, 上海, 广州, 深圳] 自动去重[^3] ``` 2. **TreeSet自然排序** ```java Set<Integer> scores = new TreeSet<>(); scores.add(85); scores.add(90); scores.add(78); System.out.println(scores); // 输出:[78, 85, 90] 自动排序 ``` ### 二、对象排序实践 3. **实现Comparable接口(自然排序)** ```java class Student implements Comparable<Student> { String name; int score; @Override public int compareTo(Student o) { return Integer.compare(this.score, o.score); // 按分数排序 } } Set<Student> stuSet = new TreeSet<>(); stuSet.add(new Student("王五", 90)); stuSet.add(new Student("李四", 85)); // 自动按分数升序排列 ``` 4. **使用Comparator定制排序**(引用[2]的Comparator实现) ```java Set<String> words = new TreeSet<>((s1, s2) -> s2.length() - s1.length()); // 按字符串长度降序排列 words.add("apple"); words.add("banana"); words.add("cat"); System.out.println(words); // 输出:[banana, apple, cat][^2] ``` ### 三、集合运算练习 5. **集合交集/并集/差集** ```java Set<Integer> setA = new HashSet<>(Arrays.asList(1,2,3)); Set<Integer> setB = new HashSet<>(Arrays.asList(2,3,4)); // 交集 setA.retainAll(setB); // 结果:[2,3] // 并集 setA.addAll(setB); // 结果:[1,2,3,4] // 差集 setA.removeAll(setB); // 结果:[1] ``` ### 四、高级应用示例 6. **统计单词频率** ```java String text = "this is a test text test"; Set<String> uniqueWords = new HashSet<>(Arrays.asList(text.split(" "))); System.out.println("Unique words count: " + uniqueWords.size()); ``` 7. **线程安全的有序集合** ```java Set<String> concurrentSet = new ConcurrentSkipListSet<>(); concurrentSet.add("A"); concurrentSet.add("C"); concurrentSet.add("B"); System.out.println(concurrentSet); // 保持线程安全的有序状态 ``` ### 推荐练习方向 1. 实现一个去重且保留插入顺序的集合(LinkedHashSet) 2. 编写比较器实现多字段排序(先按年龄降序,再按姓名升序) 3. 使用Stream API操作Set集合 4. 实现两个超大集合的高效交集运算
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值