HashSet 源码解读

简介: 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;
    }


目录
相关文章
|
存储 Java
每日一道面试题之HashSet的实现原理~
每日一道面试题之HashSet的实现原理~
|
6月前
|
安全
HashSet(源码解读)
HashSet(源码解读)
25 0
|
7月前
|
存储 缓存 Java
LinkedList 源码解读
LinkedList 源码解读
44 1
|
7月前
ArrayList源码解读
ArrayList源码解读
28 1
|
存储 Java
【面试题精讲】比较 HashSet、LinkedHashSet 和 TreeSet 三者的异同
【面试题精讲】比较 HashSet、LinkedHashSet 和 TreeSet 三者的异同
|
7月前
|
存储 安全 Java
Java集合篇之set,面试官:请说一说HashSet、LinkedHashSet、TreeSet的区别?
Java集合篇之set,面试官:请说一说HashSet、LinkedHashSet、TreeSet的区别?
49 0
|
存储 算法 Java
HashSet源码剖析
HashSet源码剖析
66 0
【JavaSE】TreeSet与TreeMap源码解读
文章目录 1 TreeSet 1.1 TreeSet快速入门 1.2 TreeSet比较机制源码解读 2 TreeMap 2.1 TreeMap快速入门 2.2 TreeMap比较机制源码解读 写在最后
【JavaSE】TreeSet与TreeMap源码解读
|
存储 Java 程序员
深究HashSet
HashSet底层原理梳理总结
142 0
Java集合源码剖析——基于JDK1.8中HashSet、LinkedHashSet的实现原理
Java集合源码剖析——基于JDK1.8中HashSet、LinkedHashSet的实现原理
Java集合源码剖析——基于JDK1.8中HashSet、LinkedHashSet的实现原理