Home > Java > javaTutorial > What is the difference between LinkedHashMap and HashMap in java

What is the difference between LinkedHashMap and HashMap in java

WBOY
Release: 2023-05-02 08:31:06
forward
1143 people have browsed it

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());
    }
}
Copy after login

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).

What is Java

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template