集合
框架关系图:
Collection接口下面有三个子接口:List、Set、Queue。此篇是关于Set<E>的简单学习总结。
补充:HashTable父类是Dictionary,不是AbstractMap。
Set:
Set里存放的对象是无序,不能重复的,集合中的对象不按特定的方式排序,只是简单地把对象加入集合中(可以存空元素)。常见的子类:HashSet、TreeSet、LinkedHashSet。
1、HashSet(无序,不可重复):
底层实际上是一个无序,不可重复的HashMap,源代码如下:
1 private transient HashMap<E,Object> map;
2 /**
3 * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
4 * default initial capacity (16) and load factor (0.75).
5 *(默认初始容量是16,加载因子是0.75,元素个数超过16*0.75就扩容)
6 */
7 public HashSet() {
8 map = new HashMap<>();
9 }
10 public HashSet(Collection<? extends E> c) {
11 map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16));
12 addAll(c);
13 }
因为Set的无序,不可重复,所以常用来去重。
1 public static void main(String[] args) {
2 Set<String> hash = new HashSet<String>();
3 hash.add("C");
4 hash.add("A");
5 hash.add("A");
6 hash.add("D");
7 hash.add("B");
8 hash.add("B");
9 hash.add("D");
10 hash.add("C");
11 Iterator it = hash.iterator();
12 while (it.hasNext()) {
13 System.out.println(it.next());
14 }
15 }
注意:当HashSet调用add(Object o)时,会把参数当为key,默认一个对象最为value:
1 private static final Object PRESENT = new Object();
2 public boolean add(E e) {
3 return map.put(e, PRESENT)==null;
4 }
2、LinkedHashSet(有序,不可重复):
LinkedHashSet继承HashSet,默认初始容量:16,加载因子:0.75。其实LinkedHashSet就是双向链状的HashSet,因为是链状,所以实现了有序性,但是不可重复。
1 public static void main(String[] args) {
2 Set<String> linked = new LinkedHashSet<String>();
3 linked.add("A");
4 linked.add("A");
5 linked.add("C");
6 linked.add("B");
7 linked.add("D");
8 linked.add("A");
9 linked.add("B");
10 Iterator it = linked.iterator();
11 while (it.hasNext()) {
12 System.out.println(it.next());
13 }
14 }
3、TreeSet(有序,不可重复):
TreeSet底层是TreeMap:
1 public class TreeSet<E> extends AbstractSet<E> implements NavigableSet<E>, Cloneable, java.io.Serializable{
2
3 private transient NavigableMap<E,Object> m;
4
5 private static final Object PRESENT = new Object();
6
7 TreeSet(NavigableMap<E,Object> m) {
8 this.m = m;
9 }
10
11 public TreeSet() {
12 this(new TreeMap<E,Object>());
13 }
TreeSet中有个Compare比较器,会对数据进行排序:
1 public static void main(String[] args) {
2 Set<String> tree = new TreeSet<>();
3 tree.add("A");
4 tree.add("C");
5 tree.add("A");
6 tree.add("D");
7 tree.add("B");
8 Iterator<String> it = tree.iterator();
9 while(it.hasNext()){
10 System.out.println(it.next());
11 }
12 }