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的实现原理~
|
5月前
|
安全
HashSet(源码解读)
HashSet(源码解读)
17 0
|
6月前
ArrayList源码解读
ArrayList源码解读
21 1
|
6月前
|
存储 安全 Java
Java集合篇之set,面试官:请说一说HashSet、LinkedHashSet、TreeSet的区别?
Java集合篇之set,面试官:请说一说HashSet、LinkedHashSet、TreeSet的区别?
43 0
|
存储 算法 Java
HashSet源码剖析
HashSet源码剖析
57 0
|
存储 安全 Java
源码剖析之ArrayList
ArrayList 是一个数组队列,相当于 动态数组。与Java中的数组相比,它的容量能动态增长。它继承于AbstractList,实现了List, RandomAccess, Cloneable, java.io.Serializable这些接口。
88 0
|
存储 算法
面试题:说一下HashMap和HashSet的实现原理?
面试题:说一下HashMap和HashSet的实现原理?
93 0
Java集合源码剖析——基于JDK1.8中HashSet、LinkedHashSet的实现原理
Java集合源码剖析——基于JDK1.8中HashSet、LinkedHashSet的实现原理
Java集合源码剖析——基于JDK1.8中HashSet、LinkedHashSet的实现原理
|
存储 安全 算法