Map is an important data structure, and this article will show you how to use different maps, such as hashmap,treemap,hashtable and Linkedhashmap.
MapOverview
There are four common map implementations in Java, Hashmap,treemap,hashtable and Linkedhashmap, and we can use a sentence to describe each map as follows:
- HASHMAP: Based on the hash list implementation, is unordered;
- TREEMAP: Based on red and black trees, sorted by key;
- Linkedhashmap: The insertion order is saved;
- Hashtable: Is synchronous, similar to HashMap;
HashMap
If the HashMap key is an object of its own definition, it is generally necessary to override the Equals () and Hashcode () methods, and to follow the conventions between them.
PackageSimplejava;ImportJava.util.HashMap;ImportJava.util.Map.Entry;classDog {String color; Dog (String c) {color=C; } PublicString toString () {returnColor + "Dog"; }} Public classQ26 { Public Static voidMain (string[] args) {HashMap<dog, integer> HashMap =NewHashmap<dog, integer>(); Dog D1=NewDog ("Red"); Dog D2=NewDog ("Black"); Dog D3=NewDog ("White"); Dog D4=NewDog ("White"); Hashmap.put (D1,10); Hashmap.put (D2,15); Hashmap.put (D3,5); Hashmap.put (D4,20); //Print sizeSystem.out.println (Hashmap.size ()); //Loop HashMap for(Entry<dog, integer>Entry:hashMap.entrySet ()) {System.out.println (Entry.getkey (). toString ()+ " - " +Entry.getvalue ()); } }}
Result output:
4
White dog-5
Red dog-10
White dog-20
Black dog-15
Note that we accidentally added two "white dogs", but HashMap still stores it. This is unreasonable, and now we are puzzled how many white dogs are deposited in the hashmap,5 or 20.
In fact, the dog class should be defined like this:
class Dog { String color; Dog (String c) { = c; } Public Boolean equals (Object o) { return (DOG) o). Color.equals (This. color); } publicint hashcode () { return color.length (); } public String toString () { return color + "dog"; }}
Result output:
3
Red dog-10
White dog-20
Black dog-15
The reason is that because HashMap does not allow two identical elements to be deposited, by default, the Hashcode () and Equals () of object are used to determine whether two objects are the same. The default Hashcode () method returns a different value for different objects, and the Equals () method returns true only if two references are equal, that is, when they point to the same object. If you are not sure, you can check the relationship between Hashcode () and Equals () yourself.
For example, the most commonly used methods of hashmap, such as Iteration,print, can be examined.
TreeMap
TreeMap is sorted by key, let's look at the following code to see the "Sort by key" idea.
PackageSimplejava;ImportJava.util.Map.Entry;ImportJava.util.TreeMap;classDog {String color; Dog (String c) {color=C; } Public Booleanequals (Object o) {return(DOG) O). Color.equals ( This. color); } Public inthashcode () {returncolor.length (); } PublicString toString () {returnColor + "Dog"; }} Public classQ26 { Public Static voidMain (string[] args) {Dog D1=NewDog ("Red"); Dog D2=NewDog ("Black"); Dog D3=NewDog ("White"); Dog D4=NewDog ("White"); TreeMap<dog, integer> TreeMap =NewTreemap<dog, integer>(); Treemap.put (D1,10); Treemap.put (D2,15); Treemap.put (D3,5); Treemap.put (D4,20); for(Entry<dog, integer>Entry:treeMap.entrySet ()) {System.out.println (Entry.getkey ()+ " - " +Entry.getvalue ()); } }}
Result output:
Exception in thread "main" Java.lang.ClassCastException:simplejava. Dog cannot is cast to java.lang.Comparable
At Java.util.TreeMap.compare (treemap.java:1188)
At java.util.TreeMap.put (treemap.java:531)
At Simplejava. Q26.main (q26.java:34)
Since TreeSet is based on key ordering, objects that are key must be compared to each other, which is why key needs to implement the comparable interface. For example, you can use a string as a key, because string already implements the comparable interface.
Now, let's change the dog so that it can be compared as follows:
PackageSimplejava;ImportJava.util.Map.Entry;ImportJava.util.TreeMap;classDogImplementsComparable<dog>{String color; intsize; Dog (String C,ints) {color=C; Size=s; } PublicString toString () {returnColor + "Dog"; } @Override Public intcompareTo (Dog o) {returnO.size- This. Size; }} Public classQ26 { Public Static voidMain (string[] args) {Dog D1=NewDog ("Red", 30); Dog D2=NewDog ("Black", 20); Dog D3=NewDog ("White", 10); Dog D4=NewDog ("White", 10); TreeMap<dog, integer> TreeMap =NewTreemap<dog, integer>(); Treemap.put (D1,10); Treemap.put (D2,15); Treemap.put (D3,5); Treemap.put (D4,20); for(Entry<dog, integer>Entry:treeMap.entrySet ()) {System.out.println (Entry.getkey ()+ " - " +Entry.getvalue ()); } }}
Results Print:
Red dog-10
Black dog-15
White dog-20
In this example, we sort by the size of the dog;
If "Dog D4 = new Dog" ("white", 10); " is replaced with "dog D4 = new Dog" ("white", 40); ", the result will be output as follows:
White dog-20
Red dog-10
Black dog-15
White dog-5
This is because the current TreeMap uses CompareTo () to compare keys, and different size means different dogs.
HashTable
Refer to the Java documentation: HashMap is basically similar to Hashtable, except for non-synchronous and null-enabled.
Linkedhashmap
Linkedhashmap is a subclass of HashMap, which means that it inherits the characteristics of HashMap, and in addition, LINKEDHASHMAP also preserves the insertion order.
Let's use the same code and replace the HashMap with Linkedhashmap, as follows:
PackageSimplejava;ImportJava.util.LinkedHashMap;ImportJava.util.Map.Entry;classDog {String color; Dog (String c) {color=C; } Public Booleanequals (Object o) {return(DOG) O). Color.equals ( This. color); } Public inthashcode () {returncolor.length (); } PublicString toString () {returnColor + "Dog"; }} Public classQ26 { Public Static voidMain (string[] args) {Dog D1=NewDog ("Red"); Dog D2=NewDog ("Black"); Dog D3=NewDog ("White"); Dog D4=NewDog ("White"); Linkedhashmap<dog, integer> linkedhashmap =NewLinkedhashmap<dog, integer>(); Linkedhashmap.put (D1,10); Linkedhashmap.put (D2,15); Linkedhashmap.put (D3,5); Linkedhashmap.put (D4,20); for(Entry<dog, integer>Entry:linkedHashMap.entrySet ()) {System.out.println (Entry.getkey ()+ " - " +Entry.getvalue ()); } }}
Output Result:
Red dog-10
Black dog-15
White dog-20
If we use HashMap, the result is as follows, except that the insertion order is not saved:
Red dog-10
White dog-20
Black dog-15
Read more: ArrayList vs. LinkedList vs. Vector
Link: http://www.programcreek.com/2013/03/hashmap-vs-treemap-vs-hashtable-vs-linkedhashmap/
"Simple Java" HashMap vs TreeMap vs Hashtable vs Linkedhashmap