Not long ago the interviewer let me talk about how to understand the Java data Structure framework, before also read some of the source code, Balabala told a bunch, now summed up.
Java.util package three important interfaces and features: List(list), set (guaranteed element unique in the set), Map (Maintain multiple Key-value key-value pairs, guaranteed key unique). The implementations of the different subclasses vary, such as whether they are synchronized (thread-safe) and ordered.
Common class inheritance Tree:
The following combination of source code to explain the principle of common classes and the differences between each other.
-
Collection (interface for all collection classes)
List, set are inherited from the collection interface, view the JDK API, operations collection commonly used methods are defined in the interface.
-
Collections (Tool class for manipulating collections)
The operation of the collection class has to refer to the tool class collections, which provides many convenient methods, such as the difference set of two sets, the set, the copy, the sorting and so on.
because most of the collection interface implementation classes are not synchronized, you can use the Collections.synchronized* method to create a synchronized collection class object.
To create a synchronized list:
List synList = Collections.synchronizedList(new ArrayList());
The principle of its implementation is to re-encapsulate the new object, manipulating the object with the keyword synchronized synchronization. See the source code is easy to understand.
Collections Part Source:
//collections.synchronizedlist Returns an instance of the static class Synchronizedcollection and eventually assigns the new ArrayList object to the Collection<e> C. StaticClass Synchronizedcollection<e> implements Collection<e>, Serializable {FinalCollection<e> C;//backing Collection FinalObject Mutex;//Object on which to synchronizeSynchronizedcollection (collection<e> c) {if(c==NULL)Throw NewNullPointerException (); This. C = C; Mutex = This; }//... Public Boolean Add(e) {a simple call to the original ArrayList object when working on the collection, just synchronizing synchronized(mutex) {returnC.add (e);} }//...}
-
List (lists)
-
ArrayList, vector is a linear table, using an object array as a container to store data, adding a lot of methods to maintain the array, so that its capacity can be dynamically increased, greatly improving the development efficiency. The obvious difference is that the ArrayList is non-synchronous and the vectors are synchronous. You should use ArrayList to improve efficiency when you do not consider multi-threading.
ArrayList, Vector part of the source code:
//arraylist.add Public Boolean Add(e) {ensurecapacityinternal (size +1);//increments modcount!! //You can see that the added object is placed in the Elementdata array.elementdata[size++] = e;return true;}//arraylist.remove PublicERemove(intIndex) {rangecheck (index); modcount++; E OldValue = elementdata (index);intnummoved = Size-index-1;if(Nummoved >0)//Remove an element when an array of empty space is created by the System.arraycopy method moves all subsequent elements forward one bit, System.arraycopy calls the local method provided by the virtual machine to increase efficiencySystem.arraycopy (Elementdata, index+1, Elementdata, index, nummoved); Elementdata[--size] =NULL;/Let GC do it work returnOldValue;}the//vector Add method has more synchronized keywords Public synchronized Boolean Add(e) {modcount++; Ensurecapacityhelper (Elementcount +1); elementdata[elementcount++] = e;return true;}
-
LinkedList is a linked list, a little understanding of the data structure to know its implementation principle. The random location of a linked list is faster than a linear table when inserting, deleting data, and traversing slower than a linear table.
Schematic diagram of a doubly linked list:
LinkedList Part Source:
//Source code is clearly expressed in the schematic diagram Public class LinkedList<E>extends abstractsequentiallist< E>implements List<e;, Deque<e;, Cloneable, java. io. Serializable { //Tail node transientNode<e> first;transientNode<e> last;}//Node class Private Static class Node<E> { //node-stored dataE item; Node<e> Next; Node<e> prev; Node (node<e> prev, E element, node<e> next) { This. item = element; This. next = Next; This. prev = prev; }}
This allows you to select the use of ArrayList (non-synchronous, infrequent deletion when selected), Vector (Select when synchronization is required), LinkedList (select when inserting and deleting frequently at any location).
-
MAP (store key value pairs, key unique)
-
The HASHMAP structure is implemented by encapsulating the put-in Key-value into a entry object stored in a entry array, where the position (array subscript) is computed from the hash value of the key and the length of the array. If the array is currently subscript with a value, the current value of the array is pointed to the newly added entry object.
A little dizzy, look at the picture:
Look at the chart and then see the source code, very clear, no need to comment.
Public class HashMap<k,V>extends abstractmap<k ,v>implements Map<K,v;, cloneable, Serializable { transientEntry<k,v>[] table; PublicVput(K key, V value) {if(Key = =NULL)returnPutfornullkey (value);inthash = hash (key);inti = indexfor (hash, table.length);//traverse the current subscript's entry object chain and replace if key already exists for(entry<k,v> e = table[i]; E! =NULL; E = E.next) {Object k;if(E.hash = = Hash && (k = e.key) = = Key | | key.equals (k))) {V oldValue = E.value; E.value = value; E.recordaccess ( This);returnOldValue; }} addentry (hash, key, value, I);return NULL; }}StaticClass Entry<k,v> implements Map.entry<k,v> {FinalK key; V value; Entry<k,v> Next;inthash;}
-
TreeMap is a red-black tree composed of entry objects, with comparator to compare the size of the key. Red black Tree Online A lot of information, I can not tell, here is not introduced.
-
Set (guarantees element uniqueness within the container)
The first reason to speak map is because the set structure is to maintain a map to store data, using the MAP structure key value uniqueness .
HashSet Part Source:
Public class HashSet<e>extends abstractset<e> Implements Set<E;, cloneable, java. io. Serializable { //Meaningless object to be the value of map Private Static FinalObject PRESENT =NewObject (); Public Boolean Add(e) {returnMap.put (e, PRESENT) = =NULL; }}
HashSet, TreeSet respectively maintain a hashmap, TreeMap.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Java common data structure and principle analysis