This article only analyzes some of the principles and the characteristics of the collection class, does not analyze the source code, is designed to have a general understanding of the Java Collection class, understand the different types of associations and differences, so that everyone in different environments to learn to choose different classes to deal with.
The collection class in Java contains a lot of content and is very important, many of the data storage and processing (sorting, deduplication, filtering, etc.) need to be done through the collection class.
First, there are two major branches of the collection class in Java:
(1) Collection (2) Map
Let's look at their class diagram first:
(1) Collection
Collection
(2) Map
Map
Can see their relationship between the complex, if not a systematic study, and really do not know what the difference, how to choose. Since HashSet's internal implementation principle is the use of HashMap, our learning route is to learn the Map collection class first and then to learn the collection collection class.
(1) HashMap and Hashtable (note that table is a lowercase t, do not understand why so, always write wrong ...) )
First look at HashMap and Hashtable, the two brothers are often put together to compare, then they have what is different?
A.hashmap is not thread-safe, Hashtable is thread-safe, and its thread safety is implemented through Sychronize.
B. For the above reasons, hashmap efficiency is higher than Hashtable.
The C.hashmap key can be null,hashtable.
D. In a multithreaded environment, it is usually not hashtable, because it is inefficient. HASHMAP implements thread safety with the collections tool class. At the same time there are concurrenthashmap can choose, this class of thread security is implemented through lock, so efficiency is higher than Hashtable.
Well, after comparing their different, to talk about their principles.
Array, linked list, hash table. Each has advantages and disadvantages, by the way, the array of contiguous memory space, Find Fast, and delete slowly; The list makes full use of memory, storage space is discontinuous, the first and the next node to store information, so addressing trouble, find slow, but adding and removing fast; hash table, combined with them two a bit, a hash table, Consists of arrays and linked lists. Suppose that a linked list has 1000 nodes, and now finds the last node, it has to traverse from the first to the last one, and if you use a hash table, divide the list into 10 groups, and use a capacity of 10 arrays to store the 10 set of linked list header nodes (a[0] = 0, a[1] = 200, a[2 )。 This way the address is fast.
HashMap implementation principle is the above principle, of course, its specific implementation there are many other things. Hashtable the same thing, it's just a synchronous process.
Hash collisions, different keys can calculate the same value according to the hash algorithm, if the same is called collision.
Optimization measures:
(1) The cost of HashMap is very large, to create a new bucket array, and then to re-hash all the elements in the bucket once, almost equal to the re-execution of all the elements put. So if we have a range for the size of the map, it can be constructed at a given size, and the general size is set to: (int) ((float) expectedsize/0.75f + 1.0F).
(2) key design is as concise as possible.
HashMap some feature implementations:
A. Sorting by value
HashMap sorted by value by collections the Sort method, before implementing the sort, let's look at some of the HashMap traversal methods:
Collection and Map
public static void Testcm () {
Collection
Map<integer, string> hs = new Hashmap<integer, string> ();
int i = 0;
Hs.put (199, "Serial number:" +201);
while (I<50) {
Hs.put (i, "Serial number:" +i);
i++;
}
Hs.put (-1, "Serial number:" +200);
Hs.put (200, "Serial number:" +200);
Traversal mode one: For each traverse HashMap's entryset, note that this method must be written when defined
Map<integer, string> HS, cannot be written as map HS;
For (Entry<integer, string> entry:hs.entrySet ()) {
System.out.println ("Key:" +entry.getkey () + "value:" +entry.getvalue ());
}
Traverse mode Two: Use EntrySet's iterator
Iterator<map.entry<integer, string>> Iterator = Hs.entryset (). Iterator ();
while (Iterator.hasnext ()) {
Entry<integer, string> Entry = Iterator.next ();
System.out.println ("Key:" +entry.getkey () + "value:" +entry.getvalue ());
};
Traverse mode three: For each directly using HashMap's keyset
For (Integer Key:hs.keySet ()) {
System.out.println ("Key:" +key+ "Value:" +hs.get (key));
};
Traverse mode four: Use Keyset's iterator
Iterator keyiterator = Hs.keyset (). Iterator ();
while (Keyiterator.hasnext ()) {
Integer key = (integer) keyiterator.next ();
System.out.println ("Key:" +key+ "Value:" +hs.get (key));
(1) The use of keyset two ways will traverse two times, so efficiency is not used EntrySet high.
(2) HashMap output is unordered, this disorder does not mean that each traversal results in a different order, but rather different from the insertion order.
Next we look at the sorting by value, note the details of the comparison will not repeat the process.
Sort the HashMap
public static void Sorthashmap (Map<integer, string> HashMap) {
System.out.println ("post-sorting");
The first step is to construct a linkedlist with HashMap.
Set<entry<integer, string>> sets = Hashmap.entryset ();
Linkedlist<entry<integer, string>> linkedlist = new Linkedlist<entry<integer, String>> (sets) ;
Sort by the sort method of collections
Collections.sort (LinkedList, New Www.thd178.com/Comparator<Entry<Integer, string>> () {
@Override
public int Compare (Entry<integer, string> O1, Entry<integer, string>www.2018yulpt.com O2) {
TODO auto-generated Method Stub
/*string Object1 = (String) o1.getvalue ();
String object2 = (string) o2.getvalue ();
Return Object1.compareto (OBJECT2); */
Return O1.getvalue (). CompareTo (O2.getvalue ());
}
});
The third step is to assign the sorted list to Linkedhashmap
Map<integer, string> map = new Linkedhashmap ();
For (Entry<integer, string> entry:linkedlist) {
Map.put (Entry.getkey (), Entry.getvalue ());
}
For (Entry<integer, string> entry:map.entrySet ()) {
System.out.println ("Key:" +entry.getkey () + "value:" +entry.getvalue ());
B. Sort by key
HashMap key sorting is easier to implement than sorting by value, and there are many methods, as described below.
The first: the familiar formula or the familiar flavor, using the collections sort method, just change the comparison rules.
The second kind: TreeMap is the key sort, the default ascending, so it can be implemented by TreeMap.
public static void Sorthashmapbykey (Map hashmap) {
System.out.println ("After key sorting");
First step: Create a TreeMap instance, and the constructor passes in a comparator object.
Treemap<integer, string> TreeMap = new Treemap<integer, string> (new comparator<integer> () {
@Override
public int Compare (Integer O1,integer O2) {
TODO auto-generated Method Stub
Return Integer.compare (O1, O2);
}
});
Step Two: Add the hashmap that will be sorted to the treemap we constructed.
Treemap.putall (HashMap);
For (Entry<integer, string> entry:treemap.entrySet ()) {
System.out.println ("Key:" +entry.getkey () + "value:" +entry.getvalue ());
The Third kind: can take out all the key through the keyset, then the key sorts, then the orderly Key-value key value pair to the Linkedhashmap, this does not stick the code, has the interest can oneself to try.
C.value to Heavy
For HashMap, its key cannot be duplicated, but its value can be duplicated, and sometimes we have to remove the duplicated part.
Method One: The HashMap key-value swapped, and then assigned to a new HashMap, due to the non-repeatability of key, this time the duplicate values are removed. Finally, the newly obtained HashMap Key-value can be swapped again.
D.hashmap thread Synchronization
The first type:
Map<integer, string> hs = new Hashmap<integer, string> (www.ccyl178.com/);
HS = COLLECTIONS.SYNCHRONIZEDMAP (HS);
1
2
The second type:
Concurrenthashmap<integer, string> hs = new Concurrenthashmap<integer, string> ();
1
(2) Identifyhashmap
Identityhashmap is basically similar to HashMap, except that when two keys are strictly equal, that is, Key1==key2, it considers the two keys to be equal. Identityhashmap also allows NULL, but does not guarantee the order of key-value pairs.
(3) Weakhashmap
Weakhashmap and HashMap are basically the same, except that the latter's key retains a strong reference to the object, that is, as long as the HashMap object is not destroyed, the object referenced by all key objects is not garbage collected. HashMap also does not automatically delete the key-value pair objects for these keys. However, the objects referenced by the Weakhashmap key are not referenced by other strongly referenced variables, and the objects referenced by these keys may be recycled. Each key object in the Weakhashmap holds a weak reference to the actual object, and when the actual object corresponding to the key is reclaimed, Weakhashmap automatically deletes the key-value pair for that key.
Next is the collection interface and its subclasses:
(4) ArrayList, LinkedList, Vector
(1) First of all, talk about their relationship and differences. ArrayList and Vector are all implemented by arrays, while Linklist is implemented by double-linked lists, so ArrayList and vectors are relatively high in search efficiency, and their efficiency is lower; LinkedList is just the opposite. ArrayList is thread insecure, vector is thread-safe, and efficiency is certainly not ArrayList high. In fact, it is not usually used in vector, can do thread synchronization, can also use collections with ArrayList to achieve thread synchronization.
(2) Tips
The high cost of the expansion is mentioned many times before, so if you can determine the approximate range of capacity can be specified when creating an instance, note that this is limited to ArrayList and vector yo:
ArrayList ArrayList = new ArrayList (www.xyyulept.com100);
Arraylist.ensurecapacity (200);
Vector vector = new vector (100);
Vector.ensurecapacity (200);
(3) Other function realization
A. Sort
The sort of list is to use the collections sort method, constructs the comparator or lets the list object implements the Comparaable to be possible, here does not post the code.
B. Go heavy
The first kind: Use iterator traversal, traverse out to put in a temporary list, put before use contains to judge.
The second type: using the set of non-repeatability, only three steps away.
First step: Use the characteristics of hashset to weigh
HashSet tempset = new HashSet (arrayList);
Step two: Clear the ArrayList
Tempset.clear ();
Step three: Re-assign to list after heavy
Arraylist.addall (Tempset);
(5) Stack
Stack, is inherited from the vector, so use AH, thread safety and so on is similar to vector, but there are several places to note:
First: Add () and push (), stack is the last element as the top of the stack, so these two methods for the stack is no different, but their return value is not the same, add () returns a Boolean, that is, the addition succeeded; push () The element that you added is returned. Push is recommended for readability and for losing contact with the stack.
Second: Peek () and Pop (), both methods can get stack top element, the difference is that peek () is only read, the original stack has no effect; pop (), literally can understand, out of the stack, so the stack top element of the original stack is gone.
(6) HashSet and TreeSet
Set set class is characterized by the ability to go to the weight, their internal implementation is based on the map, with the map key, so know why you can repeat it.
Since to go to heavy, so long need to compare, since to compare, so long need to understand how to compare, otherwise it will 1 equals 2, what do you do?
Comparisons are based on the Hascode () method and the Equals () method, so the two methods need to be re-used if necessary.
Well, when it's time to summarize, you'll find that the collection classes look much, but they're very regular. Arraylist,linkedlist a disorder, an orderly, a disorder, an order, a hashmap,linkedhasmmap, a disorder, an orderly, a vector and a hashtable, The stack is thread-safe, but inefficient, and thread-insecure classes can work with collections to get thread-safe classes.
First, there are two main branches of the collection class in Java