Detailed explanation of java HashMap, TreeMap and LinkedHashMap
During the interview this morning, I asked about Java and Map related things. I remembered the content related to HashMap and TreeMap wrongly. When I came back, I quickly tried a few demos to understand.
package Map; import java.util.*; public class HashMaps { public static void main(String[] args) { Map map = new HashMap(); map.put("a", "aaa"); map.put("b", "bbb"); map.put("c", "ccc"); map.put("d", "ddd"); Iterator iterator = map.keySet().iterator(); while (iterator.hasNext()) { Object key = iterator.next(); System.out.println("map.get(key) is :" + map.get(key)); } Hashtable tab = new Hashtable(); tab.put("a", "aaa"); tab.put("b", "bbb"); tab.put("c", "ccc"); tab.put("d", "ddd"); Iterator 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 tmp = new TreeMap(); tmp.put("a", "aaa"); tmp.put("b", "bbb"); tmp.put("c", "ccc"); tmp.put("d", "ddd"); tmp.put("a", "aba"); Iterator iterator_2 = tmp.keySet().iterator(); while (iterator_2.hasNext()) { Object key = iterator_2.next(); System.out.println("tmp.get(key) is :" + tmp.get(key)); } LinkedHashMap<String,Integer> linkedHashMap = new LinkedHashMap<String,Integer>(); linkedHashMap.put("dasdsa", 1); linkedHashMap.put("gdsf",2); linkedHashMap.put("texvdfd", 3); linkedHashMap.put("bdada", 4); linkedHashMap.put("gdsf",3); for(String temp: linkedHashMap.keySet()){ System.out.println(temp); } } } Map is different from List. The underlying layer uses the form of key-value pairs to store data. Map.Entry is an internal sub-entry. Different implementations of Map have different index schemes for key-value pairs.
HashMap itself uses hash function to index key values. We cannot determine the order of the last key values.
However, there is an interesting phenomenon that when using Integer as the key-value pair, when the digits are 1 digit, the key value is arranged from small to large, and when the digits rise to two digits, there may be problems.
There is a balanced tree inside TreeMap to store key-value indexes. TreeMap sorts the key values according to the comparison function. I speculate that there may be an AVLtree inside.
LinkedHashMap has a feature that the key-value pairs are sorted in the order of insertion. If there are repeated insertions, they are recorded in the order of first insertion. One of the sayings on the Internet is that there are two hashs inside the structure.
One solves the order problem, the other solves the storage problem, the correctness is to be confirmed
HashMap and TreeMap are the two most commonly used Map structures. Generally speaking, HashMap is relatively efficient and the most common. Only if we need to be ordered with key values, we will use TreeMap.
Thank you for reading, I hope it can help you. Thank you for your support for this site!