跳到主要内容

Java Set 集合

Set 集合是 Java 中的一种特殊的集合,它不允许集合中出现重复元素。Set 集合中的元素是无序的,不可重复的,没有索引。

Set 集合本身的定义是一个接口类型,但是其下可以使用 HashSet、TreeSet 等实现,其中 HashSet 提供了最快的查找和插入速度,而 TreeSet 则提供了有序的元素组织。Set 集合的常用方法有 add()remove()contains()isEmpty() 等。

HashSet 集合

HashSet 是 Java 中的一种 Set 接口实现,它不允许集合中有重复的元素。它使用哈希表实现,允许插入和检索操作的时间复杂度为 O(1)。

它的实现是基于哈希函数的,因此元素的存储次序与插入次序无关,而且比较两个元素时,不需要使用 equals() 方法,只需要调用 hashCode() 方法就可以判断两个元素是否相等。

它的一个优势是,它可以检测集合中的重复元素,因此不会出现重复的元素。另外,它也可以快速检索元素,因为它使用哈希函数来存储元素,因此可以快速检索元素。

示例:

// 创建一个hashset
HashSet<Integer> hs = new HashSet<>();
System.out.println("set is " + hs); // set is []

// 添加元素
hs.add(1);
hs.add(2);
hs.add(3);
System.out.println("set is " + hs); // set is [1, 2, 3]

// 删除元素
hs.remove(2);
if (hs.contains(2)) { // false
System.out.println("set contains 2");
} else {
System.out.println("set not contains 2");
}

// 判断是否为空
if (hs.isEmpty()) { // false
System.out.println("set is empty");
} else {
System.out.println("set is not empty");
}

// 获取hashset中元素数量
System.out.println("set size is " + hs.size()); // set size is 2

// 比较两个hashset是否相等
HashSet<Integer> hs2 = new HashSet<>();
hs2.add(1);
hs2.add(3);
if (hs.equals(hs2)) { // true
System.out.println("set is equal to hs2");
} else {
System.out.println("set is not equal to hs2");
}

// 计算hashset的哈希码
System.out.println("set hashcode is " + hs.hashCode()); // set hashcode is 4

// 用iterator返回一个迭代器,用于遍历hashset中的元素
Iterator<Integer> iterator = hs.iterator();
while (iterator.hasNext()) {
System.out.println("iterator: " + iterator.next());
}

// 清空hashset
hs.clear();
if (hs.isEmpty()) { // true
System.out.println("set is empty");
} else {
System.out.println("set is not empty");
}

TreeSet 集合

TreeSet 是 java.util 包中的一个集合类,它继承自 AbstractSet,是基于 TreeMap 实现的,TreeSet 中的元素是按照元素的自然顺序排序的,或者根据构造函数传入的 Comparator 进行排序的。

TreeSet 不允许集合中存在重复元素,它提供了多种操作集合元素的方法,如添加、删除、查找等,还提供了多种不同的迭代器,可以用 Iterator 或 ListIterator 迭代TreeSet 中的元素。

示例:

// 创建TreeSet对象
TreeSet<Integer> treeSet = new TreeSet<>();
// 添加元素
treeSet.add(1);
treeSet.add(2);
treeSet.add(3);
treeSet.add(4);
treeSet.add(5);
System.out.println("treeSet is " + treeSet);
// 遍历TreeSet
for (Integer element : treeSet) {
System.out.println(element);
}
// 查询最大值和最小值
System.out.println("最小值:" + treeSet.first()); // 最小值:1
System.out.println("最大值:" + treeSet.last()); // 最大值:5
// 查询比3小的最大值
System.out.println("比3小的最大值:" + treeSet.lower(3)); // 比3小的最大值:2
// 查询比3大的最小值
System.out.println("比3大的最小值:" + treeSet.higher(3)); // 比3大的最小值:4
// 查询比3小的所有值
System.out.println("比3小的所有值:" + treeSet.headSet(3)); // 比3小的所有值:[1, 2]
// 查询比3大的所有值
System.out.println("比3大的所有值:" + treeSet.tailSet(3)); // 比3大的所有值:[3, 4, 5]
// 删除元素
treeSet.remove(3);
System.out.println("删除后:" + treeSet); // 删除后:[1, 2, 4, 5]