Let's start by describing what a map is. In the array we index the content by the array subscript, and in the map we index the object by object, the object to index is called key, and its corresponding object is called value. This is what we call a key-value pair.
HashMap quickly find its content through hashcode, and all elements in TreeMap remain in a fixed order, and if you need to get an ordered result you should use TREEMAP (the order of the elements in HashMap is not fixed).
HashMap non-thread-safe TreeMap non-thread safe
Thread Safety
In Java, thread safety generally manifests itself in two ways:
1, multiple thread access to the same Java instance (read and modify) does not interfere with each other, it is mainly embodied in the keyword synchronized. such as ArrayList and Vector,hashmap and Hashtable
(The latter has synchronized keywords before each method). If you are interator a list object and the other threads remove an element, the problem arises.
2. Each thread has its own field and is not shared across multiple threads. It is mainly embodied in the Java.lang. threadlocal class, without Java keyword support, such as static, transient.
1.ABSTRACTMAP abstract class and SortedMap interface
Abstractmap abstract class: (HashMap inheritance Abstractmap) overrides the Equals () and Hashcode () methods to ensure that two equality mappings return the same hash code. The two mappings are equal if the two map sizes are equal, the same keys are included, and each key has the same value in both maps. The hash code of the map is the sum of the hash codes of the mapped elements, each of which is an implementation of the Map.entry interface. As a result, two equality mappings report the same hash code regardless of the internal order of the mappings.
SortedMap Interface: (TreeMap inherits from SortedMap) it is used to keep the key in an orderly order. The SortedMap interface provides an access method for the view (subset) of the image, including two endpoints. In addition to sorting is a key that works on a map, processing SortedMap is the same as dealing with SortedSet. The element added to the SortedMap implementation class must implement the comparable interface, otherwise you must give its constructor an implementation of the comparator interface. The TreeMap class is its only implementation.
2. Two general map implementations
HASHMAP: Based on hash table implementation. The key classes you add with HashMap explicitly define hashcode () and Equals () [can override Hashcode () and Equals ()], and to optimize the use of hashmap space, you can tune the initial capacity and load factor.
(1) HashMap (): Build an empty hash map image
(2) HashMap (map m): Build a hash map image and add all the mappings for the images m
(3) HashMap (int initialcapacity): Constructs an empty hash map image with a specific capacity
(4) HashMap (int initialcapacity, float loadfactor): Constructs an empty hash map image with a specific capacity and load factor
TREEMAP: Based on red-black tree. TreeMap has no tuning option because the tree is always in equilibrium.
(1) TreeMap (): Building an empty image tree
(2) TreeMap (Map m): Build an image tree and add all elements in image m
(3) TreeMap (Comparator C): Build an image tree and sort the keywords using a specific comparer
(4) TreeMap (SortedMap s): Constructs an image tree, adds all the mappings in the image tree S, and sorts with the same comparer as the ordered image s
3. Two general map performance
HashMap: Applies to inserting, deleting, and locating elements in a map.
Treemap: For traversing keys (key) in natural order or in a custom order.
4. Summary
HashMap is usually faster than treemap (the data structure of the tree and hash table), it is recommended to use HashMap, and TreeMap is used when the map needs to be sorted.
Import Java.util.HashMap; Import java.util.Hashtable; Import Java.util.Iterator; Import Java.util.Map; Import Java.util.TreeMap; public class Hashmaps {public static void main (string[] args) {map<string, string> Map = new hashmap<string, St Ring> (); Map.put ("A", "AAA"); Map.put ("B", "BBB"); Map.put ("C", "CCC"); Map.put ("D", "ddd"); iterator<string> Iterator = Map.keyset (). Iterator (); while (Iterator.hasnext ()) {Object key = Iterator.next (); System.out.println ("Map.get (Key) is:" + map.get (key));} Define Hashtable, used to test hashtable<string, string> tab = new hashtable<string, string> (); Tab.put ("A", "AAA"); Tab.put ("B", "BBB"); Tab.put ("C", "CCC"); Tab.put ("D", "ddd"); iterator<string> iterator_1 = Tab.keyset (). Iterator (); while (Iterator_1.hasnext ()) {Object key = Iterator_1.next (); System.out.println ("Tab.get (Key) is:" + tab.get (key));} treemap<string, string> tmp = new treemap<string, string> (); Tmp.put ("A", "AAA"); Tmp.put ("B", "BBB"); Tmp.put ("C", "CCC"); Tmp.put ("D", "CDC"); iterator<string> iterator_2 = Tmp.keyset (). Iterator (); while (Iterator_2.hasnext ()) {Object key = Iterator_2.next (); System.out.println ("Tmp.get (Key) is:" + tmp.get (key));}}}
The results of the operation are as follows:
Map.get (key) is:D DD
Map.get (Key) is:bbb
Map.get (Key) IS:CCC
Map.get (Key) is:aaa
Tab.get (Key) is:bbb
Tab.get (Key) is:aaa
Tab.get (key) is:D DD
Tab.get (Key) IS:CCC
Tmp.get (Key) is:aaa
Tmp.get (Key) is:bbb
Tmp.get (Key) IS:CCC
Tmp.get (Key) IS:CDC
The results of the hashmap are not sorted, and the results of the TREEMAP output are well sequenced.
The following is the subject of this article. Let me give you an example of how to use HashMap:
Import java.util.*; public class Exp1 {public static void main (string[] args) {HashMap h1=new HashMap (); Random r1=new random (); for (int i=0;i<1000;i++) {integer t=new integer (r1.nextint), if (H1.containskey (t)) ((Ctime) h1.get (t)). count++; else H1.put (T, new Ctime ()); } System.out.println (H1); }} class ctime{int count=1; public String toString () {return integer.tostring (count);}}
Using get () to get value in HashMap, inserting Value,containskey () through put () is used to verify that the object already exists. It can be seen that, compared with ArrayList's operation, HashMap is not very different from other aspects except by indexing its contents by key.
As described earlier, HashMap is based on hashcode, there is a hashcode () method in the superclass object of all objects, but it does not apply to all cases like the Equals method, so that we need to rewrite our own hashcode () method. Here's an example:
Import java.util.*; public class Exp2 {public static void main (string[] args) {HashMap h2=new HashMap (), for (int i=0;i<10;i++) H2.put (new Element (i), New Figureout ()); System.out.println ("H2:"); System.out.println ("Get The result for Element:"); Element test=new Element (5); if (H2.containskey (test)) System.out.println ((figureout) h2.get (test)); else System.out.println ("not Found"); }} class element{int number; public Element (int n) {number=n;}} class figureout{random r=new Random (); Boolean possib Le=r.nextdouble () >0.5; Public String toString () {if (possible) return "ok!"; else return "impossible!";}}
In this example, element is used to index the object figureout, which means that element is key,figureout as value. A floating-point number is randomly generated in figureout, and if it is larger than 0.5, print "ok!", otherwise print "impossible!". Then see how the Figureout results for Element (3).
It turns out that no matter how many times you run, the result is "not found". This means that the index element (3) is not in HashMap. How is that possible?
The reason for this is that the Hashcode method of element inherits from object, whereas the hashcode returned by the Hashcode method in object corresponds to the current address, that is, for different objects, even if their contents are identical, The value returned with Hashcode () will also be different. This is in fact contrary to our intentions. Because we want to use the same Content Object index to get the same target object when we are using HashMap, it is necessary for hashcode () to return the same value at this time. In the example above, we expect the new Element (i) (i=5) to be the same as elementtest=newelement (5), which is actually two different objects, although their contents are the same, but they have different addresses in memory. So it is natural that the above procedure is not going to be the result of our vision. The following changes are made to the element class:
Class element{int number, public Element (int n) {number=n,} public int hashcode () {return number,} public boolean equal S (Object o) {return (o instanceof Element) && (number== (Element) O). number);}}
Here the element covers the hashcode () and Equals () methods in object. Overwrite hashcode () so that it returns as the value of number as hashcode, so that their hashcode are the same for objects of the same content. overriding Equals () is to make the result meaningful when HASHMAP determines whether two keys are equal (for overriding equals (), you can refer to my other article, "Methods in the Object class"). The results of the modified program run as follows:
H2:
Get The result for Element:
impossible!
Remember: If you want to use HashMap effectively, you will have to rewrite it in its hashcode ().
There are two principles for rewriting hashcode ():
[List=1]
You do not have to produce a unique hashcode for each different object, as long as your Hashcode method enables get () to get the contents of the put () to be put in. That is, "not a principle".
The algorithm that generates hashcode as far as possible to make the value of hashcode scattered some, not many hashcode are concentrated in one range, this is advantageous to improve hashmap performance. That is, the principle of decentralization. As for the specific reasons for the second principle, interested persons can refer to Bruce Eckel's "Thinking in Java", where there is an introduction to the principle of hashmap internal implementation, here will not repeat.
With these two principles in hand, you will be able to write your own program with good HashMap. I don't know. No, there are three methods available in Java.lang.Object: Clone (), Equals (), and hashcode () are typical, but in many cases are not applicable, they are simply the object's address to derive results. This requires us to rewrite them in our own programs, and in fact the Java class Library has rewritten hundreds of thousands of such methods. Using object-oriented polymorphism-overlay, Java's designers have built the Java architecture gracefully, and have also embodied the Java is a pure OOP language features.
The difference between HashMap and TreeMap in Java is deeply understood