HashSet 源码解读

Posted wanglongjiang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HashSet 源码解读相关的知识,希望对你有一定的参考价值。

1.创建HashSet

Set<String> set = new HashSet<>();
set.add("aaa");

2.构造方法

private transient HashMap<E,Object> map;
/**
     * 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<>();
    

3.add方法 内部通过HashMap 保证数据不重复

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

TreeSet

创建TreeSet

 Set<String> set = new TreeSet<>();
        set.add("aaa");

构造方法

private transient NavigableMap<E,Object> m;


Constructs a new, empty tree set, sorted according to the natural ordering of its elements. All elements inserted into the set must implement the Comparable interface.
Furthermore, all such elements must be mutually comparable: e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the set.
If the user attempts to add an element to the set that violates this constraint (for example, the user attempts to add a string element to a set whose elements are integers),
the add call will throw a ClassCastException.
public TreeSet() this(new TreeMap<E,Object>());


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

add方法

 public boolean add(E e) 
        return m.put(e, PRESENT)==null;
    

 

以上是关于HashSet 源码解读的主要内容,如果未能解决你的问题,请参考以下文章

HashSet的故事----Jdk源码解读

Java Review - HashMap & HashSet 源码解读

Java Review - HashMap & HashSet 源码解读

Java Review - LinkedHashMap & LinkedHashSet 源码解读

Java Review - LinkedHashMap & LinkedHashSet 源码解读

Java 数据结构HashMap和HashSet