Java Dictionary keys() 方法



描述

Java Dictionary keys() 方法获取此字典中所有键的枚举。

声明

以下是 java.util.Dictionary.keys() 方法的声明

public abstract Enumeration<K> keys()

参数

返回值

此方法返回此字典中所有键的枚举。

异常

获取整数、整数对字典的键枚举示例

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

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.keys();

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

输出

让我们编译并运行以上程序,这将产生以下结果:

2
1

获取整数、字符串对字典的键枚举示例

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

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, String> dictionary = new Hashtable<>();

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

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

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

输出

让我们编译并运行以上程序,这将产生以下结果:

2
1

获取整数、对象对字典的键枚举示例

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

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, Student> dictionary = new Hashtable<>();

      // add 2 elements
      dictionary.put(1, new Student(1, "Julie"));
      dictionary.put(2, new Student(2, "Robert"));

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

      while(enumeration.hasMoreElements()) {
         System.out.println(enumeration.nextElement());
      }
   }
}
class Student {
   int rollNo;
   String name;

   Student(int rollNo, String name){
      this.rollNo = rollNo;
      this.name = name;
   }

   @Override
   public String toString() {
      return "[ " + this.rollNo + ", " + this.name + " ]";
   }
}

输出

让我们编译并运行以上程序,这将产生以下结果:

2
1
java_util_dictionary.htm
广告