Article Directory
HashMap and TreeMap difference?
1 Overview
Generally, in the map insert, delete, positioning elements, the HashMap is the best choice.
TreeMap implements SortMap interface elements can be removed (not placed in order) in order, usually the default is naturally ascending order can customize.
So if you need to follow the natural order or custom order traversal key, then TreeMap will be better.
(The internal LinkedHashMap a linked list, can be placed in order according to the time taken to take the element)
2, code analysis
(1) HashMap taken disordered; the TreeMap natural ascending order.
Map<String,String> map=new HashMap<>();
map.put("k", "CCC");
map.put("g", "BBB");
map.put("a", "EEE");
map.put("y", "DDD");
map.put("o", "AAA");
for(String key:map.keySet()){
System.out.println(key+"-----"+map.get(key));
}
System.out.println("********************");
Map<String,String> map2=new TreeMap<>();
map2.put("k", "CCC");
map2.put("g", "BBB");
map2.put("a", "EEE");
map2.put("y", "DDD");
map2.put("o", "AAA");
for(String key:map2.keySet()){
System.out.println(key+"-----"+map2.get(key));
}
operation result:
(2) TreeMap implement custom sorting elements removed
Sort vessel analysis Recommended:
container sorting: TreeMap and TreeSet implement custom sorting to use? Difference between the two?