Set中每個元素都是唯一的,並且不保證插入元素的順序。
1. 父接口
Set繼承了Collection接口,並且具有父接口的所有方法。
2. 實現類
Set下有TreeSet、HashSet實現類,HashSet下有LinkedHashSet子類。
TreeSet
保持次序的Set,底層實現爲樹結構。可以提取出有序的序列。存放的元素必須實現Comparator接口。
TreeSet實現了SortedSet接口,該接口繼承自Set接口。
public interface SortedSet<E> extends Set<E>
public class TreeSet<E> extends AbstractSet<E> implements NavigableSet<E>,Cloneable,java.io.Serializable
新增了comparator(排序方式)、subSet(生成Set子集)、headSet(生成Set子集)、tailSet(生成Set子集)、first(返回第一個元素)、last(返回最後一個元素)方法。
HashSet
爲快速查找而設計的Set,元素必須實現hashCode()。
HashSet繼承自AbstractSet,實現了Set, Cloneable, java.io.Serializable接口。
public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, java.io.Serializable
LinkedHashSet
具有HashSet的查詢速度,且內部使用鏈表維護元素的順序。必須實現hashCode()。
LinkedHashSet繼承了HashSet,並實現Set, Cloneable, java.io.Serializable接口。
public class LinkedHashSet<E> extends HashSet<E> implements Set<E>, Cloneable, java.io.Serializable
3. 性能比較
添加元素
大小 | TreeSet | HashSet | LinkedHashSet |
---|---|---|---|
10 | 746 | 308 | 350 |
100 | 501 | 178 | 270 |
1000 | 714 | 216 | 303 |
10000 | 1975 | 711 | 1615 |
查找元素
大小 | TreeSet | HashSet | LinkedHashSet |
---|---|---|---|
10 | 173 | 91 | 65 |
100 | 264 | 75 | 74 |
1000 | 410 | 110 | 111 |
10000 | 552 | 215 | 256 |
迭代元素
大小 | TreeSet | HashSet | LinkedHashSet |
---|---|---|---|
10 | 89 | 94 | 93 |
100 | 68 | 73 | 55 |
1000 | 69 | 72 | 54 |
10000 | 69 | 100 | 58 |
可以看出HashSet性能總比TreeSet好,特別是在添加和查詢元素時,所有一般使用HashSet。除非需要一個排好序的Set時,可以使用TreeSet。
4. 與其他集合類區別
Set和List區別
見集合類-List
Set和Map區別
相同點:都繼承自Collection接口。Set元素和Map鍵值都不能重複。
不同點:Set保存單元素,Map保存鍵值對。