Java-based Set source code analysis
The Set interface and implementation class are the simplest. The simple reason is that their implementation is based on the actual map implementation. For example, hashSet is based on hashMap, TreeSet is based on TreeMap, and CopyOnWriteArraySet is based on CopyOnWriteArrayList.
Therefore, the implementation is briefly analyzed. First, let's look at the following class diagram:
Set
The Set Interface contains equal elements, which are determined by the equals method of the elements in the Set. The Set interface inherits the Collection interface, but it actually contains the same method as the Collection interface.
AbstractSet
From the class diagram, we can see that the AbstractSet interface inherits from AbstractCollection, which is an abstract Implementation of Set. However, in addition to the equals and hashcode methods, other methods are inherited (except the removeall method ). We can define a Set as follows to deepen our understanding:
Set
Set = new/***** implementation example */AbstractSet
() {/** The default implementation is to throw an exception. The variable set needs to implement this method */@ Override public boolean add (String e) {return false ;} /** the remove method must be implemented for a variable set */@ Override public Iterator
Iterator () {return new Iterator
() {Public boolean hasNext () {// TODO Auto-generated method stub return false;} public String next () {// TODO Auto-generated method stub return null ;} public void remove () {// TODO Auto-generated method stub };}@ Override public int size () {// TODO Auto-generated method stub return 0 ;}};
HashSet
It is implemented based on HashMap and has a hashMap field, as shown below:
// Implemented based on map. The key is an element and the value is a fixed PRESENTprivate transient HashMap.
Map; // map key value private static final Object PRESENT = new Object ();/*** constructor */public HashSet () {map = new HashMap <> ();}/** clear */public boolean add (E e) {return map. put (e, PRESENT) = null;}/** the Iterator is map's keySet */public Iterator
Iterator () {return map. keySet (). iterator ();}
TreeSet and CopyOnWriteArraySet
They are implemented by TreeMap and CopyOnWriteArrayList, which are not described here.