Note: The following source code is based on jdk1.7.0 _ 11
The Set set is actually an encapsulation of the map set. The map set stores key-value pairs, So we hide the values and do not expose them to the outside world. This forms the Set set.Corresponding to two very important implementations of the map set hashmap (based on the hash table), treemap (based on the red and black trees), the Set set also corresponds to two classes of hashset and treeset. Since we have spent a lot of time introducing hashmap and treemap, we will not introduce the implementation details here. Hashset in simple analysis:
Static final long serialversionuid =-5024744406713321676l; private transient hashmap <E, Object> map; // hashmap is encapsulated inside. // dummy value to associate with an object in the backing map Private Static final object present = new object (); // The value is fixed as */Public hashset () {map = new hashmap <> ();} public hashset (collection <? Extends E> C) {map = new hashmap <> (math. max (INT) (C. size ()/. 75f) + 1, 16); addall (c);} public hashset (INT initialcapacity, float loadfactor) {map = new hashmap <> (initialcapacity, loadfactor );} public hashset (INT initialcapacity) {map = new hashmap <> (initialcapacity);} hashset (INT initialcapacity, float loadfactor, Boolean dummy) {map = new linkedhashmap <> (initialcapacity, loadfactor );}
There is almost nothing to say about the method, and all of them are directly calling the hashmap method.
public boolean add(E e) { return map.put(e, PRESENT)==null; }
The value inserted by the add method is a fixed new object (). hashmap supports the null key, and hashset naturally supports it.
public boolean remove(Object o) { return map.remove(o)==PRESENT; }
Treeset:
Private transient navigablemap <E, Object> m; // dummy value to associate with an object in the backing map Private Static final object present = new object (); treeset (navigablemap <e, object> m) {This. M = m;} public treeset () {// inside is treeset this (New treemap <E, Object> ();} public treeset (comparator <? Super E> comparator) {This (New treemap <> (comparator);} public treeset (collection <? Extends E> C) {this (); addall (c);} public treeset (sortedset <E> S) {This (S. comparator (); addall (s );}
Note that because treeset does not support the null key, treeset does not support the null key. This should be distinguished from hashset.
public boolean add(E e) { return m.put(e, PRESENT)==null; } public boolean remove(Object o) { return m.remove(o)==PRESENT; }
The Set set has very few practical applications. You can understand the principle.
[Source code] Set set source code analysis