Java 简明教程

Java Hashtable Class

Introduction

Java Hashtable 类实现了散列表,它将键映射到值。以下是有关 Hashtable 的重要要点−

The Java Hashtable class implements a hashtable, which maps keys to values.Following are the important points about Hashtable −

  1. In this any non-null object can be used as a key or as a value.

  2. If many entries are to be made into a Hashtable, creating it with a sufficiently large capacity may allow the entries to be inserted more efficiently than letting it perform automatic rehashing as needed to grow the table.

Class declaration

以下是 java.util.Hashtable 类声明−

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

public class Hashtable<K,V>
   extends Dictionary<K,V>
   implements Hashtable<K,V>, Cloneable, Serializable

Class constructors

Class methods

Methods inherited

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

This class inherits methods from the following classes −

  1. java.util.Object

Adding a Mapping to a HashTable of Integer, Integer Pair Example

以下示例说明了 Java Hashtable put() 方法的使用,可将一些值放到一个 Hashtable 中。我们创建了 Integer-Integer 对的 Hashtable 对象。然后,使用 put() 方法添加一些条目,然后打印表。

The following example shows the usage of Java Hashtable put() method to put few values in a Hashtable. We’ve created a Hashtable object of Integer,Integer pairs. Then few entries are added using put() method and then table is printed.

package com.tutorialspoint;

import java.util.Hashtable;

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

      // create hash table
      Hashtable<Integer,Integer> hashtable = new Hashtable<>();

      // populate hash table
      hashtable.put(1, 1);
      hashtable.put(2, 2);
      hashtable.put(3, 3);

      System.out.println("Hashtable elements: " + hashtable);
   }
}

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

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

Hashtable elements: {3=3, 2=2, 1=1}