HashSet的实现
其实HashSet是通过HashMap实现的,虽然HashSet实现的是Set接口,在继承关系上面与Map无关,但实现上却是相关的:
//HashSet构造器源码
public HashSet() {
map = new HashMap<>();
}
HashMap是有键值对的,但是HashSet只有一个值,是怎么实现的呢?请看源码:
private static final Object PRESENT = new Object();
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
通过add()方法的源码,我们可以看到,是直接将HashMap的value置为一个空的Object类,来实现。
HashSet特点
与HashMap相同,Set是无序、不可重复的,实例:
public class Test {
public static void main(String args[]) {
Set<String> s = new HashSet<String>();
s.add("a");
s.add("b");
s.add("c");
System.out.println(s);
s.add("b"); //相同的元素不会被加入
System.out.println(s);
}
}
---------------------------------------------
输出结果为:
[a, b, c]
[a, b, c]