Java container & generic: V. Self-white of HashMap and TreeMap, java container
Writer: BYSocket)
Weibo: BYSocket
Douban: BYSocket
The Java container article should be the last one: the Java container series. Today, the bricklayer chatted about Maps.
1. Review of Map
Map, also known as ing table, is an object that maps keys to values. There are four Map sets that implement the Map interface and are frequently used: HashMap, TreeMap, Hashtable and LinkedHashMap.
Bricklayer memory palace:
1. A ing does not contain duplicate keys.
2. Each key can only be mapped to one value.
Ii. HashMap
HashMap is implemented based on the Map interface of the hash table. The hash function can only apply to keys. The following is an example of a company employee and employee search:
?
| 123456789101112131415161718 |
import java.util.HashMap;import java.util.Map; class Employee{} public class HaspMap01{ public static void main(String[] args) { Map<String, Employee> employees = new HashMap<String, Employee>(); employees.put("1206010035", new Employee()); System.out.println(employees); String number = "1206010035"; System.out.println(employees.get(number)); }} |
Run, you can see the result: put method, you can add the key-value ing to the table. The get method returns the value mapped to the specified key. From their hashCode, we can see that it is the same object.
The key of HaspMap must be unique, and the same key cannot store two values. If you call the put method twice for the same key, the second value replaces the first value. The null value and the null key are also allowed. The following is a simple example:
?
| 123456789101112131415161718 |
package javaBasic.collection.map; import java.util.HashMap;import java.util.Map;public class HaspMap02{ @SuppressWarnings({ "unchecked", "rawtypes" }) public static void main(String[] args) { Map map = new HashMap<String, String>(); map.put(null, "null01"); map.put(null, "null02"); System.out.println(map); System.out.println(map.get(null)); }} |
The result is as follows:
?
It can be seen that the first value is replaced by the second value.
There are three important aspects of HashMap:
1. HashMap Constructor
The HaspMap constructor involves two parameters: initial capacity and loading factor. The initial capacity is the bucket content when the hash table is created. A load factor is a scale in which a hash table can reach full capacity before its capacity increases automatically. Both parameters affect the performance of HashMap. A default initial capacity (16) and default loading Factor (0.75) are constructed by default ). The default loading Factor (. 75) is a compromise between time and space costs.
2. Similar to the Set summarized last time, the HashMap thread is not in sync. If you want to prevent exceptions, set it to synchronization:
?
| 1 |
Map m = Collections.synchronizedMap(new HashMap(...)); |
3. If the synchronization fails, a concurrent modification exception occurs.
The following is a complex example:
?
| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
package javaBasic.collection.map; import java.util.HashMap;import java.util.Map.Entry; class A{ public boolean equals(Object obj) { return true; }} class B{ public int hashCode() { return 1; }} class C{ public int hashCode() { return 2; } public boolean equals(Object obj) { return true; }} public class HashMap03{ public static void main(String[] args) { HashMap<A, Integer> hashMapA = new HashMap<A, Integer>(); hashMapA.put(new A(), 10); hashMapA.put(new A(), 5); System.out.println("HashMapA Elements:"); System.out.print("\t" + hashMapA + "\n"); // loop HashMapA for(Entry<A, Integer> entryA : hashMapA.entrySet()) { System.out.println(entryA.getKey().toString()+"-"+entryA.getValue()); } HashMap<B, Integer> hashMapB = new HashMap<B, Integer>(); hashMapB.put(new B(), 10); hashMapB.put(new B(), 5); System.out.println("HashMapB Elements:"); System.out.print("\t" + hashMapB + "\n"); // loop HashMapB for(Entry<B, Integer> entryB : hashMapB.entrySet()) { System.out.println(entryB.getKey().toString()+"-"+entryB.getValue()); } HashMap<C, Integer> hashMapC = new HashMap<C, Integer>(); hashMapC.put(new C(), 10); hashMapC.put(new C(), 5); System.out.println("HashMapC Elements:"); System.out.print("\t" + hashMapC + "\n"); // loop HashMap for(Entry<C, Integer> entryC : hashMapC.entrySet()) { System.out.println(entryC.getKey().toString()+"-"+entryC.getValue()); } }} |
Run the command to view the following results:
It can be seen that the neutralizationJava container & generic: 3. The knowledge points involved in the comparison of HashSet, TreeSet, and javashashset are the same:
To judge the equality of two elements in a set, not only the equals method, but also the return values of the hashCode () method must be equal.
3. TreeMap
TreeMap uses a tree structure (a red-black tree). Elements in the set are sorted, but the complexity of adding, deleting, and including algorithms is O (log (n )). In fact, the Map features are basically consistent. For example, let's look at the following simple example:
?
| 12345678910111213 |
public class TreeMap01{ @SuppressWarnings({ "rawtypes", "unchecked" }) public static void main(String[] args) { Map map = new TreeMap(); map.put("1", "1"); map.put("4", "4"); map.put("2", "2"); map.put("2", "3"); System.out.println(map); }} |
The result is as follows:
?
We can see that
1. TreeMap implements SortedMap, which, as its name implies, is a sorted set.
2. The same key cannot store two values. If you call the put method twice for the same key, the second value replaces the first value.
Iv. Summary
HashMap and TreeMap 1. HashMap quickly searches for its content through hashcode, while all elements in TreeMap maintain a fixed order, if you need to get an ordered result, you should use TreeMap (the arrangement order of elements in HashMap is not fixed ). The order of elements in HashMap is not fixed ). 2. HashMap uses hashcode to quickly search its content, while all elements in TreeMap maintain a fixed order, if you need to get an ordered result, you should use TreeMap (the arrangement order of elements in HashMap is not fixed ). The Collection framework provides two general Map implementations: HashMap and TreeMap (the SortedMap interface implemented by TreeMap ). 3. insert, delete, and locate elements in Map. HashMap is the best choice. However, if you want to traverse keys in the natural or custom order, it is better to use TreeMap. The key classes required to be added using HashMap clearly define the implementation of hashCode () and equals. This TreeMap has no optimization options because the tree is always in the balance state.
Writer: BYSocket)
Weibo: BYSocket
Douban: BYSocket