Set不同实现类的对比及Set无序性、不可重复性的原理
在Java中,Set是一个集合接口,用于存储不重复
元素的集合。不同的Set实现类有不同的特点和适用场景。
一、常见实现类
1. HashSet
- 使用哈希表实现,不保证元素的顺序。
- 查找、插入和删除操作的时间复杂度为O(1)。
允许存储null元素
。
import java.util.*;
public class CollectionExample {
public static void main(String[] args) {
// HashSet示例
HashSet<String> hashSet = new HashSet<>();
hashSet.add("Apple");
hashSet.add("Banana");
hashSet.add("Orange");
System.out.println("\nHashSet:");
for (String item : hashSet) {
System.out.println(item);
}
}
}
2. LinkedHashSet
- 继承自HashSet,内部使用
双向链表
维护插入顺序。 - 具有HashSet的查找、插入和删除操作的性能,同时保持了插入顺序。
允许存储null元素
。
import java.util.*;
public class CollectionExample {
public static void main(String[] args) {
// LinkedHashSet示例
LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>();
linkedHashSet.add("Red");
linkedHashSet.add("Green");
linkedHashSet.add("Blue");
System.out.println("\nLinkedHashSet:");
for (String color : linkedHashSet) {
System.out.println(color);
}
}
}
3. TreeSet
- 基于
红黑树
实现,元素按照自然顺序或指定Comparator进行排序。 - 查找、插入和删除操作的时间复杂度为O(log n)。
不允许存储null元素
。
二、无序性和不可重复性
- 无序性:Set接口的实现类并不保证元素的顺序,即元素存储的顺序与添加顺序或元素的大小关系无关。HashSet和TreeSet是无序的,而
LinkedHashSet会保持元素的插入顺序
,是因为底层使用了双向链表。 - 不可重复性:Set接口保证集合中的元素不重复,即同一个元素只能存储一次。这是通过
元素的
equals()方法和hashCode()方法 来判断元素是否重复的。
上一篇 Java——TreeMap、Properties的使用。 |
欢迎点赞、收藏、评论!!!
| 下一篇 StringBuffer与StringBuilder的常用方法及源码分析。 |