跳转至

Set集合

定义

Set是Java中不允许重复元素的无序集合接口,它继承自Collection接口,主要用于存储不重复的元素集合。

作用

Set集合在实际开发中具有以下重要价值:

  1. 去重存储:自动去除重复元素,保证元素唯一性
  2. 快速查找:基于哈希表实现,提供O(1)的查找性能
  3. 集合运算:支持交集、并集、差集等数学集合运算
  4. 灵活实现:提供多种实现类满足不同需求
  5. 类型安全:保证集合中元素类型的一致性

图表说明

例子

import java.util.HashSet;
import java.util.TreeSet;
import java.util.Arrays;
import java.util.Set;

public class SetDemo {
    public static void main(String[] args) {
        // HashSet示例
        Set<String> hashSet = new HashSet<>();
        hashSet.add("Apple");
        hashSet.add("Banana");
        hashSet.add("Apple"); // 重复元素不会被添加

        System.out.println("HashSet:");
        System.out.println("大小: " + hashSet.size()); // 2
        System.out.println("包含Orange吗? " + hashSet.contains("Orange"));

        // TreeSet示例(自动排序)
        Set<Integer> treeSet = new TreeSet<>();
        treeSet.add(5);
        treeSet.add(2);
        treeSet.add(8);

        System.out.println("TreeSet(自动排序):");
        for(int num : treeSet) {
            System.out.println(num); // 输出顺序: 2,5,8
        }

        // 常用操作
        Set<String> fruits = new HashSet<>(Arrays.asList("Apple", "Banana", "Orange"));
        Set<String> tropical = new HashSet<>(Arrays.asList("Banana", "Mango", "Pineapple"));

        // 并集
        Set<String> union = new HashSet<>(fruits);
        union.addAll(tropical);
        System.out.println("并集: " + union);

        // 交集
        Set<String> intersection = new HashSet<>(fruits);
        intersection.retainAll(tropical);
        System.out.println("交集: " + intersection);

        // 差集
        Set<String> difference = new HashSet<>(fruits);
        difference.removeAll(tropical);
        System.out.println("差集: " + difference);
    }
}

执行结果

HashSet:
大小: 2
包含Orange吗? false
TreeSet(自动排序):
2
5
8
并集: [Apple, Mango, Pineapple, Orange, Banana]
交集: [Banana]
差集: [Apple, Orange]