The interface and implementation class of set is the simplest, and the simple reason is that its implementation is based on the actual map implementation. such as HashSet based on Hashmap,treeset based on Treemap,copyonwritearrayset based on Copyonwritearraylist.
Therefore, it realizes the brief analysis. First look at the following class diagram:
Set
The meaning of the set interface is that it contains equal elements, and equality is determined by the Equals method of the elements within the collection. The set interface inherits the collection interface, but in fact it contains the same method as the collection interface.
Abstractset
As can be seen from the class diagram, the Abstractset interface inherits from the Abstractcollection, which is the abstract implementation of set, but in addition to the Equals and Hashcode methods, other methods are inherited (RemoveAll method). We can customize the set schematic as follows to deepen its understanding:
set<string> set = new/** * * Implementation Example * /abstractset<string> () {/ * * default implementation to throw exception , a mutable collection needs to implement this method * /@Override public boolean Add (String e) { return false; } /* * Variable collection requires implementation of the Remove method * /@Override public iterator<string> Iterator () { return new Iterator<string> () {public Boolean hasnext () { //TODO auto-generated method stub return false;< c21/>} 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 based on the HASHMAP implementation and has an internal field hashmap as follows:
Based on the map implementation, the key is the element, the value is fixed presentprivate transient hashmap<e,object> map; The key value of map 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; } /** iterators are map keySet * /Public iterator<e> Iterator () { return Map.keyset (). Iterator ();
TreeSet and Copyonwritearrayset
They are given to TreeMap and Copyonwritearraylist respectively, and are not mentioned here.
A brief analysis of Java set source code