HashSet 的常见用法及对应源码介绍

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就很简单了。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值