首页 文章资讯内容详情

Java中的字典方法

2026-06-04 1 花语

字典是一个抽象类,代表一个键/值存储库,其操作非常类似于Map。给定键和值,您可以将值存储在Dictionary对象中。一旦存储了值,就可以使用其键检索它。因此,就像映射一样,字典可以看作是键/值对的列表。

以下是字典定义的方法,如下所示-

序号方法与说明1个Enumerationelements()

Returnsanenumerationofthevaluescontainedinthedictionary.

2Objectget(Objectkey)

返回包含与键关联的值的对象。如果键不在字典中,则返回空对象。

3booleanisEmpty()

Returnstrueifthedictionaryisempty,andreturnsfalseifitcontainsatleastonekey.

4枚举keys()

返回字典中包含的键的枚举。

5Objectput(Objectkey,Objectvalue)

Insertsakeyanditsvalueintothedictionary.Returnsnullifthekeyisnotalreadyinthedictionary;returnsthepreviousvalueassociatedwiththekeyifthekeyisalreadyinthedictionary.

6Objectremove(Objectkey)

删除键及其值。返回与键关联的值。如果键不在字典中,则返回null。

7intsize()

返回字典中的条目数。

以下是实现Dictionary类的put()和get()方法的示例-

示例

import java.util.*; public class Demo { public static void main(String[] args) { Dictionary dictionary = new Hashtable(); dictionary.put("20", "John"); dictionary.put("40", "Tom"); dictionary.put("60", "Steve"); dictionary.put("80", "Kevin"); dictionary.put("100", "Ryan"); dictionary.put("120", "Tim"); dictionary.put("140", "Jacob"); dictionary.put("160", "David"); System.out.println("Value at key 20 = " + dictionary.get("20")); System.out.println("Value at key 40 = " + dictionary.get("40")); System.out.println("Value at key 30 = " + dictionary.get("30")); System.out.println("Value at key 90 = " + dictionary.get("90")); } }

输出结果

Value at key 20 = John Value at key 40 = Tom Value at key 30 = null Value at key 90 = null

让我们看看另一个示例,其中我们也使用elements()方法显示Dictionary值-

示例

import java.util.*; public class Demo { public static void main(String[] args) { Dictionary dictionary = new Hashtable(); dictionary.put("20", "John"); dictionary.put("40", "Tom"); dictionary.put("60", "Steve"); dictionary.put("80", "Kevin"); dictionary.put("100", "Ryan"); dictionary.put("120", "Tim"); dictionary.put("140", "Jacob"); dictionary.put("160", "David"); System.out.println("Dictionary Values..."); for (Enumeration i = dictionary.elements(); i.hasMoreElements();) { System.out.println(i.nextElement()); } System.out.println("Value at key 20 = " + dictionary.get("20")); System.out.println("Value at key 40 = " + dictionary.get("40")); System.out.println("Value at key 30 = " + dictionary.get("30")); System.out.println("Value at key 90 = " + dictionary.get("90")); } }

输出结果

Dictionary Values... Tom Jacob Steve Ryan David John Kevin Tim Value at key 20 = John Value at key 40 = Tom Value at key 30 = null Value at key 90 = null