java - 什么是 LinkedHashMap<k, v>?

标签 java generics collections linked-list

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

最佳答案

A LinkedHashMap is a combination of hash table and linked list. It has a predictable iteration order (a la linked list), yet the retrieval speed is that of a HashMap. The order of the iteration is determined by the insertion order, so you will get the key/values back in the order that they were added to this Map. You have to be a bit careful here, since re-inserting a key does not change the original order.

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

关于java - 什么是 LinkedHashMap<k, v>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6140856/

相关文章:

c# - 避免集合已修改错误

c# - 如何解决 GetEnumerator 推迟的调用?

Java Set 获取重复项

c# - PropertyInfo.SetValue() 不工作但没有错误

c# - 与 C# 泛型的协变

java - 正则表达式替换java中的特定字符

java - 使用 -source 7 或更高版本来启用钻石运算符

java - 如何指定maven的distributionManagement组织范围?

java - 我可以将字符串转换为整数或为其赋值吗?

c# - 我可以将泛型设为可选,默认为某个类吗?