1、介绍
HashSet是一个没有重复元素的集合,无序的,他事通过HashMap实现的,所以他也是线程不安全的。接下来介绍使用。
2、使用
1、构造方法
HashSet<Integer> hashSet = new HashSet<>();
HashSet<Integer> hashSet2 = new HashSet<>(20);
HashSet<Integer> hashSet3 = new HashSet<>(20,0.8f);
HashSet<Integer> hashSet4 = new HashSet<>(hashSet);
HashSet是由hashmap实现的,里面会有一个hashmap的对象来完成各种操作,所以这里4个构造方法刚好也是调用了hashmap的几个构造方法。
public HashSet() {
map = new HashMap<>();
}
public HashSet(Collection<? extends E> c) {
map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16));
addAll(c);
}
public HashSet(int initialCapacity, float loadFactor) {
map = new HashMap<>(initialCapacity, loadFactor);
}
public HashSet(int initialCapacity) {
map = new HashMap<>(initialCapacity);
}
这篇博客关于hashmap 的源码介绍就不讲了,上一篇博客已经对hashmap的源码进行了详细的讲解,hashmap懂了过后再看这个就很简单了。
2、添加操作
hashSet.add(1); //增加元素
//这里也是调用了hashmap中的put方法实现添加操作
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
这里hashset其实就是hashmap中key的集合,所以添加的元素其实就是添加key。
3、删除操作
hashSet.remove(1); //删除对应元素
hashSet.clear();
//也是调用了hashmap的删除操作
public boolean remove(Object o) {
return map.remove(o)==PRESENT;
}
public void clear() {
map.clear();
}
4、查找操作
hashSet.contains(2);
源码:
//调用hashmap中是否包含key的方法
public boolean contains(Object o) {
return map.containsKey(o);
}
5、遍历操作
①、迭代器遍历
Iterator<Integer> iterator = hashSet.iterator();
while(iterator.hasNext()){
System.out.print(iterator.next());
}
②、foreach遍历,先转为数组
Integer[] arr = (Integer[]) hashSet.toArray(new Integer[0]);
for (Integer integer : arr) {
System.out.print(integer);
}
这样hashset的常见用法就介绍完了,因为hashset完全就是hashmap实现的,所以理解了hashmap后hashset就很简单了。