[Java Collections Framework] 浅析java 集合框架(七) : Set,HashSet,LinkedHashSet,TreeSet

其实这部分只需要一句话,你就明白了,HashSet 的底层是一个HashMap, 也就是说所有操作都和HashMap一样,就将value 设为了 一个固定的Object。。。。,同理TreeSet也一样,所以源代码不足500 行,而HashMap一个文件就接近3000行

Set interface

这部分比较有意思的是他提供的交并补操作

  • s1.containsAll(s2) — returns true if s2 is a subset of s1. (s2 is a subset of s1 if set s1 contains all of the elements in s2.)
  • s1.addAll(s2) — transforms s1 into the union of s1 and s2. (The union of two sets is the set containing all of the elements contained in either set.)
  • s1.retainAll(s2) — transforms s1 into the intersection of s1 and s2. (The intersection of two sets is the set containing only the elements common to both sets.)
  • s1.removeAll(s2) — transforms s1 into the (asymmetric) set difference of s1 and s2. (For example, the set difference of s1 minus s2 is the set containing all of the elements found in s1 but not in s2.)

equals

这个方法是直接用的AbtractSet 中的 equals 方法,即判断两个集合相等其实是判断他们包含相同的元素,这个在 eclipse 里面跟踪一下就能找到了

    /**
     * Compares the specified object with this set for equality.  Returns
     * <tt>true</tt> if the given object is also a set, the two sets have
     * the same size, and every member of the given set is contained in
     * this set.  This ensures that the <tt>equals</tt> method works
     * properly across different implementations of the <tt>Set</tt>
     * interface.<p>
     *
     * This implementation first checks if the specified object is this
     * set; if so it returns <tt>true</tt>.  Then, it checks if the
     * specified object is a set whose size is identical to the size of
     * this set; if not, it returns false.  If so, it returns
     * <tt>containsAll((Collection) o)</tt>.
     *
     * @param o object to be compared for equality with this set
     * @return <tt>true</tt> if the specified object is equal to this set
     */
    public boolean equals(Object o) {
        if (o == this)
            return true;

        if (!(o instanceof Set))
            return false;
        Collection<?> c = (Collection<?>) o;
        if (c.size() != size())
            return false;
        try {
            return containsAll(c);// 是set,size相等,并且有相同的元素,则两个set相同
        } catch (ClassCastException unused)   {
            return false;
        } catch (NullPointerException unused) {
            return false;
        }
    }

HashSet

如我第一段写的底层就是个HashMap, 关于HashMap的分析请见[Java Collections Framework] 浅析java 集合框架(五) : Map,HashMap,LinkedHashMap

我们看一看,HashSet 的filed就ok 了

    private transient HashMap<E,Object> map; // 底层数据结构,

    // Dummy value to associate with an Object in the backing Map
    private static final Object PRESENT = new Object();// 所有key 映射成 PRESENT

TreeSet

这个也一样,基于TreeMap

TreeMap 的分析
[Java Collections Framework] 浅析java 集合框架(六) : TreeMap

猜你喜欢

转载自blog.csdn.net/Dylan_Frank/article/details/81304382