您的当前位置:首页java中LinkedHashMap和HashMap区别

java中LinkedHashMap和HashMap区别

2024-07-16 来源:乌哈旅游

1、说明

Map基本上可以使用HashMap,但是HashMap有一个问题,那就是迭代HashMap的顺序不是HashMap放置的顺序,就是无序。HashMap的这个缺点往往会带来麻烦,因为有些场景我们期待一个有序的Map,这就是LinkedHashMap。

2、区别实例

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

可以看到,在使用上,LinkedHashMap和HashMap的区别就是LinkedHashMap是有序的。 上面这个例子是根据插入顺序排序。LinkedHashMap还有一个参数决定是否在此基础上再根据访问顺序(get,put)排序。

以上就是java中LinkedHashMap和HashMap区别,希望对大家有所帮助。更多Java学习指路:

本教程操作环境:windows7系统、java10版,DELL G3电脑。

显示全文