美文网首页
Set(一):HashSet、LinkedHasSet源码浅析

Set(一):HashSet、LinkedHasSet源码浅析

作者: 小川君 | 来源:发表于2018-09-10 10:30 被阅读0次

HasSet

HashSet基于HashMap实现的,HashSet是一个没有重复元素的集合,其实是我们存入的值都是作为HashSet内部map的key值,value值都是一样大的

我们来看下HashSet的构造方法:

    public HashSet() {
        map = new HashMap<>();
    }
    // 传入一个Collection集合,也就是所可以将一个list/set集合转化为一个set集合
    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);
    }
    // 创建一个内部是一个LinkedHashMap的HashSet集合  不过这个构造方法不是public的
    HashSet(int initialCapacity, float loadFactor, boolean dummy) {
        map = new LinkedHashMap<>(initialCapacity, loadFactor);
    }

来简单看下addAll()

  private static final Object PRESENT = new Object();

  public boolean addAll(Collection<? extends E> c) {
        boolean modified = false;
        for (E e : c)
            if (add(e))
                modified = true;
        return modified;
    }

    public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }    

可以看到addAll()先遍历元素,然后将遍历出来的元素传入到add()里面,最后将传入的元素作为key值,保存到map对象里面,value值为默认的空对象PRESENT

HashSet中的增删改查都是基于HashMap的,所以对HashSet的操作等同于对HashMap的操作,包括迭代器

遍历HashSet的两种方式:

        LinkedList<String> arrayList = new LinkedList<>();
        arrayList.add("chuan--0");
        arrayList.add("chuan--1");
        arrayList.add("chuan--2");
        arrayList.add("chuan--3");
        arrayList.add("chuan--4");

        HashSet<String> hashSet = new HashSet<>(16,0.75f);
        for(String str: hashSet){
            Log.i("wz", "for循环: " + str);
        }
        Iterator<String> iterator = hashSet.iterator();
        while (iterator.hasNext()){
            Log.i("wz", "iterator: " + iterator.next());
        }
        
        
输出为:
517-517/com.chuan.jun I/wz: 
    for循环: chuan--3
    for循环: chuan--1
    for循环: chuan--2
    for循环: chuan--4
    for循环: chuan--0
    iterator: chuan--3
    iterator: chuan--1
    iterator: chuan--2
    iterator: chuan--4
    iterator: chuan--0

可以看到输出的元素是无序的,而不像list那样输入元素的顺序与输出元素的顺序是相同的

LinkeHashSet

LinkedHashSet继承于HashSet,其构造方法实现了HashSet中实现LinkedHashMap的构造方法,元素的正删改查完全由父类HashSet实现,所以LinkedHashSet类中除了构造方法之外,并没有其他的什么操作方法

        HashSet<String> hashSet = new LinkedHashSet<String>(16,0.75f);
        hashSet.add("chuan--0");
        hashSet.add("chuan--1");
        hashSet.add("chuan--2");
        hashSet.add("chuan--3");
        hashSet.add("chuan--4");

        for(String str: hashSet){
            Log.i("wz", "for循环: " + str);
        }

输出为:
3005-3005/com.chuan.jun I/wz:
for循环: chuan--0
for循环: chuan--1
for循环: chuan--2
for循环: chuan--3
for循环: chuan--4

可以看到相对于HashSet元素的输入顺序与输入顺序是一致的

相关文章

网友评论

      本文标题:Set(一):HashSet、LinkedHasSet源码浅析

      本文链接:https://www.haomeiwen.com/subject/pobtgftx.html