1. Description
Map can basically use HashMap, but HashMap has a problem, that is, the order of iterating HashMap is not the order in which HashMap is placed, or it is out of order. This shortcoming of HashMap often causes trouble, because in some scenarios we expect an ordered Map, which is LinkedHashMap.
2. Difference examples
public static void main(String[] args) { Map<String, String> map = new LinkedHashMap<String, String>(); map.put("apple", "苹果"); map.put("watermelon", "西瓜"); map.put("banana", "香蕉"); map.put("peach", "桃子"); Iterator iter = map.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); System.out.println(entry.getKey() + "=" + entry.getValue()); } }
As you can see, in use, the difference between LinkedHashMap and HashMap is that LinkedHashMap is ordered. The above example is sorted according to insertion order. LinkedHashMap also has a parameter that determines whether to sort based on the access sequence (get, put).
Java is an object-oriented programming language that can write desktop applications, Web applications, distributed systems and embedded system applications.
The above is the detailed content of What is the difference between LinkedHashMap and HashMap in java. For more information, please follow other related articles on the PHP Chinese website!