Java 简明教程

Java LinkedHashMap Class

Introduction

Java LinkedHashMap 类是 Map 接口的散列表和链表实现,具有可预测的迭代顺序。关于 LinkedHashMap 的重点如下:

The Java LinkedHashMap class is Hash table and Linked list implementation of the Map interface, with predictable iteration order. Following are the important points about LinkedHashMap −

  1. The class provides all of the optional Map operations, and permits null elements.

  2. The Iteration over a HashMap is likely to be more expensive.

Class declaration

以下是 java.util.LinkedHashMap 类的声明:

Following is the declaration for java.util.LinkedHashMap class −

public class LinkedHashMap<K,V>
   extends HashMap<K,V>
   implements Map<K,V>

Parameters

以下是 java.util.LinkedHashMap 类的参数:

Following is the parameter for java.util.LinkedHashMap class −

  1. K − This is the type of keys maintained by this map.

  2. V − This is the the type of mapped values.

Class constructors

Class methods

Methods inherited

此类从以下类中继承方法:

This class inherits methods from the following classes −

  1. java.util.HashMap

  2. java.util.AbstarctMap

  3. java.util.Object

  4. java.util.Map

Getting a Value from LinkedHashMap Example

以下示例显示 Java LinkedHashMap get() 方法用于从映射中基于键获取值的用法。我们创建了一个 Integer、Integer 的映射对象。然后添加一些条目,并打印映射。使用 get() 方法,检索并打印一个值。

The following example shows the usage of Java LinkedHashMap get() method to get a value based on a key from a Map. We’ve created a Map object of Integer,Integer. Then few entries are added, map is printed. Using get() method, a value is retrieved and printed.

package com.tutorialspoint;

import java.util.LinkedHashMap;

public class LinkedHashMapDemo {
   public static void main(String args[]) {

      // create hash map
      LinkedHashMap<Integer,Integer> newmap = new LinkedHashMap<>();

      // populate hash map
      newmap.put(1, 1);
      newmap.put(2, 2);
      newmap.put(3, 3);

      System.out.println("Initial map elements: " + newmap);

      System.out.println("Value: " + newmap.get(1));
   }
}

Output

让我们编译并运行以上的程序,这会生成以下结果:

Let us compile and run the above program, this will produce the following result.

Initial map elements: {1=1, 2=2, 3=3}
Value: 1