什么是LinkedHashMap<k,v>?

2022-09-03 16:44:44

好吧,我是这些HashMaps的新手,但对LinkedLists和HashMaps有一些了解。如果你能给我一些关于LinkedHashMap的简单解释,那就太好了,就像在titiile中一样,这是否意味着我们明确地将其定义为某种类型?


答案 1

LinkedHashMap是哈希表和链表的组合。它具有可预测的迭代顺序(链接列表),但检索速度是HashMap的速度。迭代的顺序由广告订单决定,因此您将按照键/值添加到此地图的顺序取回键/值。在这里必须小心一点,因为重新插入密钥不会改变原始顺序。

k 代表键,v 代表值。

/*
  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
*/

答案 2

它是两种数据结构的混合体,一种是 通过将元素添加到有权访问其近邻的节点列表的末尾来保留插入顺序,另一种是 使用存储桶数组的 ,其中键的模除余数确定起始存储桶以查询该存储桶内容列表中的键的方法。LinkedListHashMapMapListshashcode()equals()

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