什么是LinkedHashMap ?

好的,所以我是这些HashMaps的新手,但对LinkedLists和HashMaps有一些了解。 如果你能给我一些关于LinkedHashMap的简单解释并且在titile中这意味着我们明确地将它定义为某种类型会很棒吗?

LinkedHashMap是哈希表和链表的组合。 它具有可预测的迭代顺序(链接列表),但检索速度是HashMap的检索速度。 迭代的顺序由插入顺序决定,因此您将按照它们添加到此Map的顺序返回键/值。 这里你必须要小心,因为重新插入一个键不会改变原始顺序。

k代表Key,v代表Value。

/* Simple Java LinkedHashMap example This simple Java Example shows how to use Java LinkedHashMap. It also describes how to add something to LinkedHashMap and how to retrieve the value added from LinkedHashMap. */ import java.util.LinkedHashMap; public class JavaLinkedHashMapExample { public static void main(String[] args) { //create object of LinkedHashMap LinkedHashMap lHashMap = new LinkedHashMap(); /* Add key value pair to LinkedHashMap using Object put(Object key, Object value) method of Java LinkedHashMap class, where key and value both are objects put method returns Object which is either the value previously tied to the key or null if no value mapped to the key. */ lHashMap.put("One", new Integer(1)); lHashMap.put("Two", new Integer(2)); /* Please note that put method accepts Objects. Java Primitive values CAN NOT be added directly to LinkedHashMap. It must be converted to corrosponding wrapper class first. */ //retrieve value using Object get(Object key) method of Java LinkedHashMap class Object obj = lHashMap.get("One"); System.out.println(obj); /* Please note that the return type of get method is an Object. The value must be casted to the original class. */ } } /* Output of the program would be 1 */ 

它是两个数据结构的混合体, LinkedList ,通过向可以访问其直接邻居的节点列表的末尾添加元素来保留插入顺序,以及使用桶Lists数组的HashMapMap ,其中键的hashcode()的模数除法余数确定要查询位于该桶的内容列表中的键的equals()方法的起始桶。

优点是,由于LinkedList性质,您可以按插入顺序遍历HashMap中的现有元素,并且如果您在密钥查找中快速跳转到正确的存储桶(为大型集合节省了大量时间)拥有元素的关键。

这称为generics。 kv必须替换为您要存储的实际类型。 要创建一个在字符串上映射整数的HashMap,您可以编写:

  LinkedHashMap 

在Wikipedia上阅读Java中的generics 。

LinkedHashMap键与ArrayLists或数组的相似之处在于它们按插入顺序存储的方式。 普通HashMaps按其哈希码排序。

k = key v = value它们可以是任何类型。

最大的区别是LinkedHashMap是有序的。 如果使用迭代器,则键和值的顺序与它们添加到地图的顺序相同。 HashMap无法保证返回的顺序。