Java 简明教程

Java Dictionary Class

Introduction

*Java Dictionary*类是任何类的抽象父类,例如 Hashtable,它将键映射到值。以下是有关 Dictionary 的重要几点:

The Java Dictionary class is the abstract parent of any class, such as Hashtable, which maps keys to values.Following are the important points about Dictionary −

  1. In this class every key and every value is an object.

  2. In his class object every key is associated with at most one value.

Class declaration

以下是 *java.util.Dictionary*类的声明:

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

public abstract class Dictionary<K,V>
   extends Object

Class constructors

Class methods

Methods inherited

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

This class inherits methods from the following classes −

  1. java.util.Object

Adding a Mapping to Dictionary of Integer, Integer Example

以下示例显示了 Java Dictionary put(K,V) 方法的用法。我们使用 Integer、Integer 的 Hashtable 对象创建一个字典实例。然后使用 put(K,V) 方法向其中添加了一些元素。使用 elements() 方法检索枚举,然后迭代枚举以打印字典的元素。

The following example shows the usage of Java Dictionary put(K,V) method. We’re creating a dictionary instance using Hashtable object of Integer, Integer. Then we’ve added few elements to it using put(K,V) method. An enumeration is retrieved using elements() method and enumeration is then iterated to print the elements of the dictionary.

package com.tutorialspoint;

import java.util.Enumeration;
import java.util.Dictionary;
import java.util.Hashtable;

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

      // create a new hashtable
      Dictionary<Integer, Integer> dictionary = new Hashtable<>();

      // add 2 elements
      dictionary.put(1, 1);
      dictionary.put(2, 2);

      Enumeration<Integer> enumeration = dictionary.elements();

      while(enumeration.hasMoreElements()) {
         System.out.println(enumeration.nextElement());
      }
   }
}

让我们编译并运行上述程序,这将生成以下结果 −

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

2
1