一尘不染

什么是LinkedHashMap?

java

好吧,我是这些HashMap的新手,但对LinkedLists和HashMaps有所了解。如果您能给我一些有关LinkedHashMap的简单解释,那将是很好的,并且在标题上,这是否意味着我们正在明确定义它为某种类型?


阅读 298

收藏
2020-12-03

共1个答案

一尘不染

LinkedHashMap是哈希表和链接列表的组合。它具有可预测的迭代顺序(一个链表),但检索速度却是HashMap的速度。迭代的顺序由插入顺序确定,因此您将按将键/值添加到此Map的顺序来获取键/值。您在这里必须小心一点,因为重新插入密钥不会更改原始顺序。

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
*/
2020-12-03