什么是LinkedHashMap <k,v>?

Joh*_*dep 13 java generics collections linked-list

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

evi*_*one 31

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
*/
Run Code Online (Sandbox Code Playgroud)


Edw*_*uck 11

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

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