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;
    }


目录
打赏
0
1
1
0
112
分享
相关文章
每日一道面试题之HashSet的实现原理~
每日一道面试题之HashSet的实现原理~
|
8月前
|
HashSet(源码解读)
HashSet(源码解读)
35 0
LinkedList 源码解读
LinkedList 源码解读
54 1
|
9月前
ArrayList源码解读
ArrayList源码解读
40 1
【面试题精讲】比较 HashSet、LinkedHashSet 和 TreeSet 三者的异同
【面试题精讲】比较 HashSet、LinkedHashSet 和 TreeSet 三者的异同
|
9月前
|
Java集合篇之set,面试官:请说一说HashSet、LinkedHashSet、TreeSet的区别?
Java集合篇之set,面试官:请说一说HashSet、LinkedHashSet、TreeSet的区别?
57 0
史上最全的Java容器集合之ArrayList(源码解读)(二)
史上最全的Java容器集合之ArrayList(源码解读)(二)
61 1
史上最全的Java容器集合之LinkedHashMap(源码解读)
史上最全的Java容器集合之LinkedHashMap(源码解读)
342 0
史上最全的Java容器集合之LinkedHashMap(源码解读)
史上最全的Java容器集合之ArrayList(源码解读)(上)
史上最全的Java容器集合之ArrayList(源码解读)
73 0
HashSet源码剖析
HashSet源码剖析
88 0
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等