First, let's take a look at the Collection interface, which is the most fundamental of the Collection framework. Let's take a look at its Declaration public interface Collection <E> extends Iterable <E>, it can be seen that it inherits the Iterable (iteratable) interface, which means that Iterator can be used For specific implementation classes of Collection, which is also the reason why the set supports the enhanced For loop.
Here, we need to describe two concepts: Ordered and Sorted. Sorted is a special case of Ordered, that is, there is no Sorted and Unordered.
Ordered indicates that the order in which the set is accessed has been predetermined. For example, the access to the List is indicated by subscript, although the nature of HashMap and so on is also accessed in ascending order of different Hash codes, it is still difficult to predict.
Sorted means that the internal order of the set is in the natural order (such as integers and strings in the alphabet) or by the specific comparison between objects (to implement the Comparable interface, or the implementation passed to the set Comparator ).
Take a look at this interface:
It inherits the Iterable interface. These operations or actions mainly include:
(1) query operations.
Size, isEmpty, contains, iterator, and toArray are all query operations.
(2) modify the operation.
Add, Remove
(3) batch operation.
RemoveAll (the population of the latter and then the intersection), retainAll (intersection), containsAll, addAll, clear
In general, its sub-interface List, Queue, Set will be implemented, where List is Ordered, Queue is Sorted, and Set is not allowed to be repeated, if you want to implement a Bag set (repeated and Unordered are allowed), the Collection interface will be directly implemented.
The collection implementation class generally has two constructor functions, one with no parameters and the other with a collection as the parameter.
The Collection framework provides an abstract class for this interface. Besides the size and iterator, The add method is basically implemented, because the above method is related to the data structure of the specific implementation within the set.
Secondly, the list interface of ordered can use subscript to access elements in the Set in sequence.
Take a look at this interface:
Add Method
Addall (INT, collection <? Extends E>)
Get (INT)
Set (INT, E)
Add (INT, E)
Remove (INT)
Indexof (object)
Lastindexof (object)
Listiterator ()
Listiterator (INT)
Sublist (INT, INT)
Listiterator returns the iterator subinterface listiterator, And the iterator returned by listiterator (INT) starts with Int.
Similarly, for the list interface, there is an abstract class named abstractlist (inherited from abstractcollection) to complete the specific general implementation.
The add of collection has been implemented, so there are two main internal classes for this abstract class, which are actually the iterator, one is to complete the sequential traversal of collection, one is the listiterator (such as rollback) iterator with special functions.
Specific implementation classes of the List interface.
First, the famous arraylist, let's look at the class diagram:
Its essence is the implementation of an array. its own methods are mainly trimtosize and ensurecapacity, the former sets the size of the array to the actual size of the array, while the latter sets the minimum size of the array to the size required by the parameter. Another key is non-thread-safe.
There is also an implementation class of javasactlist. As a legacy product of java1.0, the list interface is implemented in Java2, but it is a thread-safe vector.
Too many methods ..., however, it is rarely maintained. For example, the lastindexof of arraylist is implemented by listiterator, while the implementation of vector is relatively simple, and reverse traversal is complete. Sun is recommended to rewrite collection frameworks, this is important because it can greatly accelerate Java applications.
Then, the queue interface is designed to hold elements with priority. It mainly adds insert, delete, and check methods. Each method has two versions and one returns an exception, returns a number. In general, the implementation classes of this interface do not allow the insertion of null, but one of its implementation classes allow the insertion of null.
Throws exception
Returns special value
Insert
Add (E)
Offer (E)
Remove
Remove ()
Poll ()
Examine
Element ()
Peek ()
It is generally FIFO, tail insertion, and header deletion.
There is an abstractqueue relative to the queue, but let's take a look at the sub-interface deque (double ended Queue) of the queue, which is actually a two-way queue, with the aim that both the beginning and end can be modified.
First element (head)
Last element (tail)
Throws exception
Special Value
Throws exception
Special Value
Insert
Addfirst (E)
Offerfirst (E)
Addlast (E)
Offerlast (E)
Remove
Removefirst ()
Pollfirst ()
Removelast ()
Polllast ()
Examine
Getfirst ()
Peekfirst ()
Getlast ()
Peeklast ()
Now, let's take a look at the abstract class abstractqueue of the FIFO queue. It provides an implementation skeleton for the queue and inherits the behavior in the abstractcollection, it is mainly used to insert, delete, and check whether an exception is thrown or the return value is implemented separately.
The following is the specific implementation class priorityqueue, which is essentially a heap-implemented priority queue. Therefore, the insertion and deletion time complexity is O (log (n )), it is required that the inserted element cannot be null, And the element must implement the comparable interface, or a comparator implementation is given. Otherwise, a classcastexception is thrown. If an element is inserted directly (no comparable or comparator) but for the set, who inserts an element directly...
Priorityqueue and its iterator
When introducing the list and queue interfaces, you must look at the abstractlist sub-abstract class abstractsequentiallist, which mainly provides a framework, use listiterator to complete the get, add, set, and remove methods.
Next, sort list, which inherits abstractsequentiallist but implements the deque and list interfaces. In fact, it is essentially a linked list implementation, but the linked list is a two-way linked list and allows null values to be inserted.
The array implementation for Bidirectional queues is arraydeque, which uses arrays. When both stacks and queues are implemented, the performance is better than the queue list.
The following are two implementations of the deque interface.
The above describes the list interface and the queue interface.
The list interface is used to randomly access subscripts, while queue is used to operate the set in a certain order.
Both use abstract classes to implement the framework, such as abstractlist and abstractqueue. The direct implementers of the two are arraylist, vector, and priorityqueue, which are somewhat special in queue, the addition of deque two-way queue enables both ends of the queue to be operated. The implementation based on this is the arraydeque implemented using arrays, And the implementation is essentially an ordered list (subclass of abstractlist abstractsequentiallist) the sort list implemented with two-way queues appears.
The next step is the map interface, because the main implementation of the set is to borrow a map with only a key, so let's take a look at the map in advance, but the map is not a subclass of the collection.
Let's take a look at the genealogy of map.
Map is defined as three Set views. The first is the Set view where duplicate Key values are not allowed, the second is the Set view of Value, and the third is the Set view, A view corresponding to a Key-Value. In general, Map cannot pass its reference to itself as the Key. If so, the stack overflows...
As you can see, the keySet method provides the Set view of the Key, and values is the Set view.
We can immediately guess that there must be a AbstractMap to implement the basic Map framework.
Specifically, the key-Value Pair maintained by AbstractMap is the SimpleEntry and SimpleImmutableEntry implemented on the Map. Entry interface. As the name suggests, the latter does not support deleting key-value pairs.
Next, we inherit the well-known HashMap from AbstractMap. HashMap allows NULL Key or Value. In the implementation of HashMap, there are two impacts on its performance, the first is the number of buckets in the HashMap initialization (a pile of objects with the same HashCode in the bucket), and the second is the loading factor, that is, the number of elements in the HashMap and the number of businesses in the volume, if the number of vendors is too large, the efficiency of HashMap will be greatly reduced, because the first step is to locate the location of the bucket (based on HashCode) and then it needs to be determined by a bunch of Equals, we didn't take advantage of Hash, so the recommended proportion is 0.75. If the number is exceeded, HashMap will re-allocate the volume, that is, increase the number of buckets.
It maintains an array of entries, that is, table. The default filling factor is 0.75, and the number of buckets is 16. The Hash algorithm is mainly implemented by hash and indexFor, if the quantity exceeds the product of the filling factor, the number of buckets is doubled.
Key methods such as put and get are commonly used.
The Put method uses the Hash algorithm to locate the Key in <Key, Value> and then randomly accesses the Entry linked list in the bucket. If K (Key. equals (K), replace the Value and return the oldValue. If no Value is found, <Key, Value>, that is, the Entry is chained into the bucket and NULL is returned, we can see that the implementation of the Hash table is the link address method.
The Get method and vice versa. Find the bucket number and then find it in the bucket.
HashMap is non-thread-safe and Unordered and UnSorted.
Take a look at the sub-class of HashMap, LinkedHashMap. This Map is very interesting. It has two main points:
First, if it is constructed by default, it is (insert-order). That is to say, it maintains a so-called insertion order in the order from start to end.
Second, if it is constructed in this way, LinkedHashMap (16, 0.75F, true) is (Access-order), which judges the iteration order according to the Access order, the latest access (access, insert) is at the end, so that it can be used to implement a LRU (least recently used ).
After reading the LinkedHashMap, we can see the IdentifyHashMap that is not commonly used. This class determines whether the element is in Map by reference, rather than Equals, therefore, the object after deserialization cannot be found, and its internal implementation does not use the link address method, but the linear Probing Method with Step 2 in the open address method.
AbstractMap also has an interesting subclass, that is, the brother of HashMap, WeakHashMap. It uses an example to illustrate it.
Map map = new WeakHashMap ();
Object x = new Object ();
Object y = new Object ();
Map. put (x, y );
X = null;
System. gc ();
System. out. println (map );
Map is empty. That is to say, once the Key object is destroyed, the Entry corresponding to the Key will be destroyed. If it is HashMap, of course it will not, because the Key in HashMap has a reference to the object, the object pointed to by the Key will not be recycled.
After reading AbstractMap and its Child classes, let's take a look at the legacy Hashtable. Generally speaking, it is mainly thread-safe and does not allow NULL keys and values. In fact, it inherits sub-Dictionary, however, the Dictionary abstract class is actually an interface and does not implement some common work at all. Therefore, when JAVA is 1.0, it is still very immature.
In addition, its default volume is 11, and its Hash algorithm is remainder. This is the standard implementation of prime numbers and remainder. But HashMap is not, and HashMap is the sum.
Map should belong to Unorder, that is, UnSorted, so we want the keys in Map to follow a certain order, such as natural order or data that implements the Comparable interface, that is, we want to have a SortedMap, then SortedMap is added as the Map sub-interface.
It requires that its subclass either implement Comparable with the inserted Key, or pass a Comparator to implement it. Otherwise, an exception is thrown...
In
After 1.6, SortedMap has a sub-interface, NavigableMap, as its name implies, that is, Map that can be navigated, that is, it can run up and down on the Key.
LowerKey/Entry or higherKey/Entry is the upper and lower traversal.
Finally, the implementation of NavigableMap, TreeMap, will not be said much. The implementation of the Red/black tree, the time complexity of query, insertion, and deletion is O (log (n )).
After finishing the introduction of Map, we start with the List View of values provided by Map, and the other is the set view of keys (exclusive and unique ).
First, let's take a look at the Set interface.
The method definitions in the Set interface are basically the same as those in the Collection, and are completely overwritten. However, it requires its implementation to be constrained by the Set in the mathematical definition.
There must be a AbstractSet to implement commonalities, but in fact AbstractSet only implements Equals and hashCode. equals uses the abstrinsall method of AbstractCollection to determine whether they are equal, hashCode returns the hashCode of all elements in the collection.
Next, implement HashSet for AbstractSet.
As you can see, HashSet aggregates a HashMap internally and uses the Set view of the Map Key.
Then, the HashSet subclass mongohashset still uses a two-way linked list to maintain the insertion sequence of the Set, but it does not have the so-called Insertion Sequence and access sequence like LinkedHashMap, it is an overloaded constructor, and then returns an implementation of the LinkedHashMap insertion sequence.
It seems that the Sorted hashset belongs to the Ordered Set, but we also want a Sorted method for the Set, so we have the Set sub-interface, SortedSet.
SortedSet requires that its elements implement the Comparable interface, or its implementation class has a Comparator implementation. After 1.6, it wants to perform up and down navigation, so NavigableSet is added.
According to the understanding of NavigableMap, lower and higher are the methods for downward and upward navigation. A specific implementation of this interface is TreeSet.
TreeSet uses a TreeMap Key view to implement its own Set view.
(From: http://weipeng2k.javaeye.com/blog)