HashMap、LinkedHash以及TreeMap源码解析

一、定义

public class HashSet<E> extends AbstractSet<E>
    implements Set<E>, Cloneable, java.io.Serializable{}

public class LinkedHashSet<E>
    extends HashSet<E>
    implements Set<E>, Cloneable, java.io.Serializable {}

public class TreeSet<E> extends AbstractSet<E>
    implements NavigableSet<E>, Cloneable, java.io.Serializable {}

abstarctset没有什么阅读价值,NavigableSet、SortSet与NavigableMap,SortMap基本一致

public abstract class AbstractSet<E> extends AbstractCollection<E> implements Set<E> {

    protected AbstractSet() {
    }


    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);
        } catch (ClassCastException unused)   {
            return false;
        } catch (NullPointerException unused) {
            return false;
        }
    }

    public int hashCode() {
        int h = 0;
        Iterator<E> i = iterator();
        while (i.hasNext()) {
            E obj = i.next();
            if (obj != null)
                h += obj.hashCode();
        }
        return h;
    }

    /**
     * 确定哪个collection长度小后,从长度大的collection中逐个删除元素
     */
    public boolean removeAll(Collection<?> c) {
        boolean modified = false;

        if (size() > c.size()) {
            for (Iterator<?> i = c.iterator(); i.hasNext(); )
                modified |= remove(i.next());
        } else {
            for (Iterator<?> i = iterator(); i.hasNext(); ) {
                if (c.contains(i.next())) {
                    i.remove();
                    modified = true;
                }
            }
        }
        return modified;
    }

}

二、底层结构
HashSet 包含一个HashMap,LinkedHashSet包含一个LinkedHashMap,TreeSet包含一个TreeMap,实现几乎都是通过HashMap的代理来实现。
三、构造器及基本实现
在学习过各种Map后,发现HashSet基本没什么难理解的地方

/*
 * 类中包含一个HashMap常量,数据结构也是HashMap,各种操作也都是通过HashMap的代理来实现
 * 所以HashSet中也可以放入一个null值,
 * 唯一需要注意的HashSet(int initialCapacity, float loadFactor,
 *  boolean dummy)这个构造器,他可以使HashSet直接拥有LinkedHashMap的底层结构,
 *  拥有了LinkedHashMap的各种特性
 */
public class HashSet<E>
    extends AbstractSet<E>
    implements Set<E>, Cloneable, java.io.Serializable
{
    static final long serialVersionUID = -5024744406713321676L;

    private transient HashMap<E,Object> map;

    // 插入map中的value值,所有map中的value值都是PRESENT
    private static final Object PRESENT = new Object();

    /**
     * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
     * default initial capacity (16) and load factor (0.75).
     */
    public HashSet() {
        map = new HashMap<>();
    }

    /**
     * 创建一个加载因子为0.75,容量最小为16且可以容纳c的HashMap
     * 看下面的add方法会发现,add元素时,只是将map中的key值添加,
     */
    public HashSet(Collection<? extends E> c) {
        //原来。75 java会自动补全啊,是java实现的吗?
        map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16));
        addAll(c);
    }

    /**
     * 创建一个容量initialCapacity,加载因子loadFactor的HashMap
     * 但是HashMap的构造器中会将容量自动扩充为2的n此幂
     */
    public HashSet(int initialCapacity, float loadFactor) {
        map = new HashMap<>(initialCapacity, loadFactor);
    }

    /**
     * 创建容量initialCapacity,加载因子0.75的HashMap
     * 但是HashMap的构造器中会将容量自动扩充为2的n此幂
     */
    public HashSet(int initialCapacity) {
        map = new HashMap<>(initialCapacity);
    }

    /**
     * 创建一个容量initialCapacity,加载因子loadFactor的LinkedHashMap
     * 但是HashMap的构造器中会将容量自动扩充为2的n此幂
     * 要LinkedHashMap有什么作用呢?为子类提供的构造器?
     * 翻到LinkedHashSet后发现果然如此,
     * 另外,HashSet通过此构造器构造后,内部结构是LinkedHashMap结构,存在了双向循环链表的许多特性。
     */
    HashSet(int initialCapacity, float loadFactor, boolean dummy) {
        map = new LinkedHashMap<>(initialCapacity, loadFactor);
    }

    /**
     * 调用map中的iterator()方法
     */
    public Iterator<E> iterator() {
        return map.keySet().iterator();
    }

    public int size() {
        return map.size();
    }

    public boolean isEmpty() {
        return map.isEmpty();
    }

    /**
     * 调用map中的containsKey方法
     */
    public boolean contains(Object o) {
        return map.containsKey(o);
    }

    /**
     * 在map中put元素,putmap的value为默认值PRESENT
     */
    public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }

    /**
     * 调用map中remove
     */
    public boolean remove(Object o) {
        return map.remove(o)==PRESENT;
    }

    /**
     * 调用map中clear
     */
    public void clear() {
        map.clear();
    }

    public Object clone() {
        try {
            HashSet<E> newSet = (HashSet<E>) super.clone();
            newSet.map = (HashMap<E, Object>) map.clone();
            return newSet;
        } catch (CloneNotSupportedException e) {
            throw new InternalError();
        }
    }

    /**
     * 序列化时,只写入了key,value没有
     */
    private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException {
        // Write out any hidden serialization magic
        s.defaultWriteObject();

        // Write out HashMap capacity and load factor
        s.writeInt(map.capacity());
        s.writeFloat(map.loadFactor());

        // Write out size
        s.writeInt(map.size());

        // Write out all elements in the proper order.
        for (E e : map.keySet())
            s.writeObject(e);
    }

    /**
     * Reconstitute the <tt>HashSet</tt> instance from a stream (that is,
     * deserialize it).
     */
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
        // Read in any hidden serialization magic
        s.defaultReadObject();

        // Read in HashMap capacity and load factor and create backing HashMap
        int capacity = s.readInt();
        float loadFactor = s.readFloat();
        //判断读入LinkedHashMap还是HashMap
        map = (((HashSet)this) instanceof LinkedHashSet ?
               new LinkedHashMap<E,Object>(capacity, loadFactor) :
               new HashMap<E,Object>(capacity, loadFactor));

        // Read in size
        int size = s.readInt();

        // Read in all elements in the proper order.
        for (int i=0; i<size; i++) {
            E e = (E) s.readObject();
            map.put(e, PRESENT);
        }
    }
}

/*
 * 只重写了几个构造方法,是生成的map为LinkedHashMap结构,
 * 生产LinkedHashSap,直接调用HashSet中特定的构造器就可以了啊
 * 这样可以使名称更加直白吧,或者有其他历史原因?
 */

public class LinkedHashSet<E>
    extends HashSet<E>
    implements Set<E>, Cloneable, java.io.Serializable {

    private static final long serialVersionUID = -2851667679971038690L;

    public LinkedHashSet(int initialCapacity, float loadFactor) {
        super(initialCapacity, loadFactor, true);
    }

    public LinkedHashSet(int initialCapacity) {
        super(initialCapacity, .75f, true);
    }

    public LinkedHashSet() {
        super(16, .75f, true);
    }

    public LinkedHashSet(Collection<? extends E> c) {
        super(Math.max(2*c.size(), 11), .75f, true);
        addAll(c);
    }
}
/*
 *TreeSet(NavigableMap<E,Object> m) 默认修饰符,不可以在TreeSet中加入map
 */
public class TreeSet<E> extends AbstractSet<E>
    implements NavigableSet<E>, Cloneable, java.io.Serializable
{
    /**
     * The backing map.
     */
    private transient NavigableMap<E,Object> m;

    // 同HashSet,map中的默认value值
    private static final Object PRESENT = new Object();

    /**
     * Constructs a set backed by the specified navigable map.
     */
    TreeSet(NavigableMap<E,Object> m) {
        this.m = m;
    }

    /**
     * 通过new TreeMap()来构建
     * 按照自然顺序排序,所以插入元素要实现comparator
     */
    public TreeSet() {
        this(new TreeMap<E,Object>());
    }

    /**
     * 通过new TreeMap(comparator)来构建
     * 按照提供的comparator排序
     */
    public TreeSet(Comparator<? super E> comparator) {
        this(new TreeMap<>(comparator));
    }

    public TreeSet(Collection<? extends E> c) {
        this();
        addAll(c);
    }

    /**
     * 与上面的TreeSet(NavigableMap<E,Object> m)对应
     * 既可以通过SortMap构建,也可以通过SortSet构建
     */
    public TreeSet(SortedSet<E> s) {
        this(s.comparator());
        addAll(s);
    }

    /**
     * 通过TreeMap代理实现
     */
    public Iterator<E> iterator() {
        return m.navigableKeySet().iterator();
    }

    /**
     * 通过TreeMap代理实现
     */
    public Iterator<E> descendingIterator() {
        return m.descendingKeySet().iterator();
    }

    /**
     * 通过map的descendingMap()获得逆序TreeMap,然后重新new TreeMap
     */
    public NavigableSet<E> descendingSet() {
        return new TreeSet<>(m.descendingMap());
    }
 public  boolean addAll(Collection<? extends E> c) {
        // TreeMap为空时,且插入collection的compartor与m的compartor相同时,
        //通过TreeMap的addAllForTreeSet来实现,
        //否则调用基本的addMap方法来实现
        //两者的区别是什么呢?
        //生产的tree结构不同,通过TreeMap.addAllForTreeSet凡是生产的是平衡二叉树,基本的addAll方法是逐个重新添加
        //两者的效率比较,肯定是TreeMap的addAllForTreeSet效率更高,没有颜色转换和旋转
        if (m.size()==0 && c.size() > 0 &&
            c instanceof SortedSet &&
            m instanceof TreeMap) {
            SortedSet<? extends E> set = (SortedSet<? extends E>) c;
            TreeMap<E,Object> map = (TreeMap<E, Object>) m;
            Comparator<? super E> cc = (Comparator<? super E>) set.comparator();
            Comparator<? super E> mc = map.comparator();
            if (cc==mc || (cc != null && cc.equals(mc))) {
                map.addAllForTreeSet(set, PRESENT);
                return true;
            }
        }
        return super.addAll(c);
    }
    public Object clone() {
        TreeSet<E> clone = null;
        try {
            //先clone TreeSet
            clone = (TreeSet<E>) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new InternalError();
        }

        //然后将TreeMap clone
        clone.m = new TreeMap<>(m);
        return clone;
    }

    private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException {
        // Write out any hidden stuff
        s.defaultWriteObject();

        // Write out Comparator
        s.writeObject(m.comparator());

        // Write out size
        s.writeInt(m.size());

        // 只写入了key, value没有
        for (E e : m.keySet())
            s.writeObject(e);
    }

    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
        // Read in any hidden stuff
        s.defaultReadObject();

        // Read in Comparator
        Comparator<? super E> c = (Comparator<? super E>) s.readObject();

        // Create backing TreeMap
        TreeMap<E,Object> tm;
        if (c==null)
            tm = new TreeMap<>();
        else
            tm = new TreeMap<>(c);
        m = tm;

        // Read in size
        int size = s.readInt();

        tm.readTreeSet(size, s, PRESENT);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值