Java 中的字典方法
java 8object oriented programmingprogramming更新于 2025/12/4 9:48:17
字典是一个抽象类,它表示一个键/值存储库,其操作方式与 Map 非常相似。给定一个键和值,您可以将值存储在字典对象中。存储值后,您可以使用其键来检索它。因此,像地图一样,字典可以被认为是键/值对的列表。
以下是字典定义的方法 −
| Sr.No | 方法 &说明 |
|---|---|
| 1 | 枚举元素() 返回字典中包含的值的枚举。 |
| 2 | Object get(Object key) 返回包含与键关联的值的对象。如果字典中没有该键,则返回一个 null 对象。 |
| 3 | boolean isEmpty( ) 如果字典为空,则返回 true,如果字典至少包含一个键,则返回 false。 |
| 4 | Enumeration keys( ) 返回字典中包含的键的枚举。 |
| 5 | Object put(Object key, Object value) 将一个键及其值插入字典。如果字典中还没有该键,则返回 null;如果键已存在于字典中,则返回与该键关联的前一个值。 |
| 6 | Object remove(Object key) 删除键及其值。返回与键关联的值。如果键不在字典中,则返回 null。 |
| 7 | int size( ) 返回字典中的条目数。 |
以下是实现 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() 方法显示字典值 −
示例
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

