For a long time, the code has been used for a lot of data lists, mainly list, and are ArrayList, feel that this thing is enough. ArrayList is used to implement a dynamic array of packaging tool classes, so write code can be pulled into the pull, iterative traversal, quite convenient.
Also do not know since when start slowly in the code will often appear hashmap and hashset and so on tool class. Should say HashMap more, and still is the interview classics question, usually also will see more. When you start to use the simple understanding is a key value corresponding table, using the key to find data is more convenient. Then, after a deep understanding, found
This thing still has a little mystery, especially the new version of the JDK to the hashmap after the tree, the code is a little complicated slightly.
Set started with less, but inadvertently found a treeset in a code, found that this class can be carried out smoothly, feel a little meaning, just slowly found that this is a good tool AH.
Code to write a lot of the sense of the importance of the foundation, so here to write a small article simple to organize some knowledge of the collection.
Okay, just sort it out:
list: That is, the list, supporting the array, linked list of functions, are generally linear
map: That is, the mapping table, stored is the key and value of the corresponding relationship
set: That is the meaning of the collection, mainly for the weight of data and sorting
Let's take a look at the list.
A list is a window for storing linear data, such as ArrayList for arrays and LinkedList for lists.
ArrayList
This is an array list, but provides the function of automatic expansion, implementation of the list interface, external operations are through the interface of the method of the declaration of Access, which is safe and convenient.
ArrayList is the key to automatic expansion, in the object initialization can be set initial capacity, can also be the default capacity. If the size of an array is not specifically specified, the initial size can be specified without specifying a size, which reduces the amount of cotton produced when dynamic expansion occurs. Speaking of which, let's say how the expansion is achieved, look at the following code:
private void Grow (int mincapacity) {
//overflow-conscious code
int oldcapacity = elementdata.length;
int newcapacity = oldcapacity + (oldcapacity >> 1);
if (newcapacity-mincapacity < 0)
newcapacity = mincapacity;
if (newcapacity-max_array_size > 0)
newcapacity = hugecapacity (mincapacity);
Mincapacity is usually close to size, and so is a win:
Elementdata = arrays.copyof (Elementdata, newcapacity);
}
Grow is a method that triggers when ArrayList adds elements or some easy to check. Main process:
1, to get the length of the array, and to move to the right, so that is equivalent to OLDCAPACITY/2, to get a new length
2, if this length is less than the minimum capacity so direct with the smallest easy
3, if greater than the maximum easy to take a maximum value, here will call a hugecapacity method, mainly compared to mincapacity and max_array_size, if mincapacity greater than Max_array_ SIZE is taken integer.max_value, otherwise take max_array_size, interesting is max_array_size take is integer.max_value-8; I don't know what it means.
4, the last is to call a replication method to copy the existing number to a new array.
Because of this replication process, if the array is larger, then always trigger the expansion of course there will be a cotton situation. So if you know the maximum at the beginning and it's easy to grow to this value, then specifying the size at the start of the initialization has a certain effect.
LinkedList
This is the list of tools for the class, the list of outstanding is added to delete what is faster, but the search will be slower.
As for the code seems to be nothing special, is a string of pointers to link up, of course, in Java in the use of objects to create a Node object, node itself points to the previous node and the latter node, which is the structure of the list:
private static class Node<e> {
E 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;
}
Then use two node to point to the head and end of the complete, the following code:
/**
* Pointer to node.
* Invariant: (a = null && last = null) | |
* (First.prev = = null && first.item!= NULL) *
*
transient node<e>
/**
* Pointer to the last node.
* Invariant: (a = null && last = null) | |
* (Last.next = = null && last.item!= NULL) *
*
transient node<e> last;
Look at an Add operation:
/**
* Links e as last element.
* *
void Linklast (e e) {
final node<e> l = last;
Final node<e> NewNode = new node<> (l, E, null);
last = NewNode;
if (L = = null),
NewNode;
else
l.next = NewNode;
size++;
modcount++;
}
The past is:
1, get to the last node and put in L
2. Create a new node, take the data to this node, and the creation process will point the prev of the new node to L, so that the chain is connected
3, and then point to the new node
4, then determine whether L is null, if it is null description is empty linked list, the new node is the first element, so that I also point to NewNode
5, if not empty, then point the L next to NewNode
6. Cumulative counter
The delete operation is also the node's front-and-back point to the move operation.
Look at the map again.
Map is the key and value to do a mapping table application, the main implementation of the class: Hashmap,hashtable,treemap
HashMap and Hashtable
Using the hash algorithm to map key values is HashMap, Hashtable is a thread-safe class with synchronization, and their two main difference is this. The principle is similar, all through the bucket + chain to combine the implementation. Bucket is used to save key, and because the hash collision reason value needs to use a linked list to store.
• Bucket meaning is efficient, through the hash calculation can be a step-by-step positioning
• The significance of the linked list is to access duplicate hash data
The specific principle has written an article "study notes: Hashtable and HashMap"
Just look at the JDK1.8 HashMap changed the storage structure, using the structure of the red-black tree, this may be to solve the problem of linked list search efficiency? There is no detailed study.
TreeMap
After looking at the TreeMap code, I found that the tree structure was still used, the red-black tree. Because the red-black tree is ordered, it naturally functions with sorting. Of course, you can also specify a comparison method by comparator to implement a specific sort.
Because it takes a tree-structured store to add and delete data, it's a bit cumbersome to look at the put code:
Public V-Put (K key, V value) {entry<k,v> t = root; if (t = = null) {Compare (key, key);//type (and possibly null) check root = new Entry<> (key, value
, null);
size = 1;
modcount++;
return null;
int CMP;
Entry<k,v> parent; Split comparator and comparable paths comparator<?
Super k> CPR = comparator;
if (CPR!= null) {do {parent = t;
CMP = Cpr.compare (key, T.key);
if (CMP < 0) T = t.left;
else if (cmp > 0) t = t.right;
else return T.setvalue (value);
while (t!= null);
else {if (key = = null) throw new NullPointerException (); @SuppressWarnings ("unchecked") comparable<?
Super k> K = (comparable<? super K>) key;
do {parent = t;
CMP = K.compareto (T.key);
if (CMP < 0) T = t.left; else if (cmp > 0) t = t.right;
else return T.setvalue (value);
while (t!= null);
} entry<k,v> e = new entry<> (key, value, parent);
if (CMP < 0) Parent.left = e;
else Parent.right = e;
Fixafterinsertion (e);
size++;
modcount++;
return null; }
1, first check whether the root node exists, there is no description is the first data, directly as the root of the tree
2, to determine whether there is a comparator, if there is a comparator to find the location of the data, if the comparator returned a result less than 0 to take the left, greater than 0 to the right, otherwise directly replace the value of the current node
3, if there is no comparator, the key is directly compared to the node's key, compared with the previous method
4. The next step is to create a child node on the parent found and put it in the left or right child node
5, Fixafterinsertion is to color the nodes
6, accumulator Processing
The remove operation also has a bit of trouble, in addition to deleting data, but also to rebalance the red-black tree.
In addition, TreeMap implements the Navigablemap<k,v> interface, so it also provides some return operations to the data collection.
Finally look at set
Set is mainly two types of applications: HashSet and TreeSet.
HashSet
The literal meaning is clear, using a set of hashes. This collection is characterized by the use of hash algorithm to save data, so the data is not duplicated, access is relatively fast. How do you do that?
Public boolean Add (E. e) {return
map.put (E, PRESENT) ==null;
}
There was a map object, and what was the map?
private transient hashmap<e,object> map;
is a hashmap, understand the hashmap to understand that such data will not repeat. Because the deposit is the 鼗 object itself as a key to save, so in the HashMap will only exist in one.
Knowing this, the other things are very clear.
TreeSet
This collection is used to sort the collection, that is, in addition to the ability to row weight, you can also bring the sorting function. Just look at the TreeSet code found that it is implemented on the basis of TreeMap. More specifically, it should be a navigablemap derived class. TreeSet is based on TreeMap when the map is not specified by default.
Public TreeSet () {This
(new treemap<e,object> ());
}
So, perhaps more concerned about the TreeSet is how to row weight? Take a look at the Add method:
Public boolean Add (E. e) {return
m.put (E, PRESENT) ==null;
}
Similar to the HashSet, it is based on the characteristics of the map to achieve the row weight. It's really simple and effective.
The above is a small series for everyone to bring more than the use of set,list,map in Java to explain all the content, I hope that we support cloud Habitat Community ~