SET详解
SET
在代码中Set是一个接口,定义方式为:
public interface Set<E> extends Collection
Set的实现类
Set常用实现类分别有:HashSet、LinkedHashSet、TreeSet、EnumSet
通用特性:
- 不能同时存在两个重复的值(当赋值重复时是覆盖还是跳过本次赋值本人并没有深入研究,从网上的资料来看更像是覆盖)
- 通过equals的方式去重,也就是说,两个对象就算变量值一样也算是两个值
HashSet
特有特性:
- hash表实现
- 无序的
HashSet实现代码
import java.util.HashSet;
import java.util.Set;
public class HashSetDemo {
public static void main(String[] args) {
//使用泛型的定义写法,确保集合里的值都是String类型
Set<String> hashSetGeneric = new HashSet<>();
//添加元素
//hashSetGeneric.add(10);//定义为10则报错,说明泛型指定类型时,赋值只能是泛型指定类型
hashSetGeneric.add("泛型Set");
hashSetGeneric.add("泛型Set");
System.out.println(hashSetGeneric);//输出[泛型Set],表明当赋值重复时,只会保存一个
//不使用泛型的定义写法,集合里可以是任意值
Set hashSet = new HashSet();
//添加Set元素
//hashSet.add(10);
hashSet.add("普通set");
hashSet.add(10);
System.out.println(hashSet);//输出[普通set, 10],表明当赋值重复时,只会保存一个
for(int i=18;i<29;i++){
hashSet.add(i);
}
System.out.println(hashSet);//输出[10, 18, 19, 20, 21, 22, 23, 普通set, 24, 25, 26, 27, 28]
// 表明HashSet的值是无序的
// 同时我们也会发现无论重复运行多少次,输出结果不变,说明hashSet的排序是通过某种方式计算出来的。
}
}
LinkHashSet
特有特性:
- 链表实现
- 有序的
LinkHashSet代码实现
import java.util.LinkedHashSet;
public class LinkedHashSetDemo {
public static void main(String[] args) {
LinkedHashSet linkedHashSet = new LinkedHashSet();
linkedHashSet.add("字符串1");
linkedHashSet.add(10);
System.out.println(linkedHashSet);//[字符串1, 10]
linkedHashSet.add("字符串2");
System.out.println(linkedHashSet);//[字符串1, 10, 字符串2]
}
}
通过以上代码我们可以发现,LinkedHashSet集合的顺序不会因为新增元素而改变,保持着添加的顺序
TreeSet
特有特性:
- 基于treeMap实现
- 有序的
- 自动进行排序
TreeSet代码实现
import java.util.TreeSet;
public class TreeSetDemo {
public static void main(String[] args) {
TreeSet tree = new TreeSet();
tree.add("A1");
tree.add("C1");
tree.add("C2");
tree.add("B2");
tree.add("B1");
System.out.println(tree);//[A1, B1, B2, C1, C2]
}
}
以上代码说明TreeSet默认对值的字符进行大小比较,并按从小到大的顺序进行排序
EnumSet
特有特性:
- 基于枚举实现
- 根据枚举顺序进行遍历
EnumSet代码实现
import java.util.EnumSet;
public class EnumSetDemo {
enum Season{
PARAM1,PARAM2,PARAM3,PARAM4
}
public static void main(String[] args) {
EnumSet es = EnumSet.allOf(Season.class);
System.out.println(es);
}
}
性能分析
功能 | EnumSet | HashSet | TreeSet | LinkedHashSet |
---|---|---|---|---|
遍历 | 4 | 2 | 1 | 3 |
查询 | 4 | 3 | 2 | 1 |
排序 | 4 | 2 | 3 | 1 |
增删 | 4 | 3 | 2 | 1 |
从上图的性能表中可以看到:在任何条件下都是EnumSet性能最高,但由于枚举的值的限制,除了一些特殊场景,在开发中很少用到。
在实际开发中最常用到的是查询、排序、增删改等功能,所以最常用的为HashSet,TreeSet