本文介绍了HashMap、LinkedHashMap 和 TreeMap 的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HashMapLinkedHashMapTreeMap 在 Java 中有什么区别?我没有看到输出有任何区别,因为所有三个都有 keySetvalues.什么是Hashtable?

What is the difference between HashMap, LinkedHashMap and TreeMap in Java?I don't see any difference in the output as all the three has keySet and values. What are Hashtables?

Map m1 = new HashMap();
m1.put("map", "HashMap");
m1.put("schildt", "java2");
m1.put("mathew", "Hyden");
m1.put("schildt", "java2s");
print(m1.keySet());
print(m1.values());

SortedMap sm = new TreeMap();
sm.put("map", "TreeMap");
sm.put("schildt", "java2");
sm.put("mathew", "Hyden");
sm.put("schildt", "java2s");
print(sm.keySet());
print(sm.values());

LinkedHashMap lm = new LinkedHashMap();
lm.put("map", "LinkedHashMap");
lm.put("schildt", "java2");
lm.put("mathew", "Hyden");
lm.put("schildt", "java2s");
print(lm.keySet());
print(lm.values());

推荐答案

所有三个类都实现了 Map 接口并提供大致相同的功能.最重要的区别是遍历条目的顺序:

All three classes implement the Map interface and offer mostly the same functionality. The most important difference is the order in which iteration through the entries will happen:

  • HashMap 绝对不保证迭代顺序.当添加新元素时,它甚至可以(并且将会)完全改变.
  • TreeMap 将根据它们的 compareTo() 方法(或外部提供的 Comparator).此外,它还实现了 SortedMap 接口,其中包含依赖此排序顺序的方法.
  • LinkedHashMap 将按照条目放入地图的顺序进行迭代
  • HashMap makes absolutely no guarantees about the iteration order. It can (and will) even change completely when new elements are added.
  • TreeMap will iterate according to the "natural ordering" of the keys according to their compareTo() method (or an externally supplied Comparator). Additionally, it implements the SortedMap interface, which contains methods that depend on this sort order.
  • LinkedHashMap will iterate in the order in which the entries were put into the map

"Hashtable" 是基于哈希的映射的通用名称.在 Java API 的上下文中,Hashtable 是在集合框架存在之前的 Java 1.1 时代一个过时的类.不应再使用它,因为它的 API 充斥着重复功能的过时方法,并且它的方法是同步的(这会降低性能并且通常无用).使用 ConcurrentHashMap 而不是 Hashtable.

"Hashtable" is the generic name for hash-based maps. In the context of the Java API,Hashtable is an obsolete class from the days of Java 1.1 before the collections framework existed. It should not be used anymore, because its API is cluttered with obsolete methods that duplicate functionality, and its methods are synchronized (which can decrease performance and is generally useless). Use ConcurrentHashMap instead of Hashtable.

这篇关于HashMap、LinkedHashMap 和 TreeMap 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-05 11:10