Dictionary
类是一个抽象类,表示键/值存储库,它的操作与Map
非常相似,但是Dictionary
已经过时了。
给定键和值,可以将值存储在Dictionary
对象中。 存储该值后,可以使用键检索它。 因此,像Map
一样,Dictionary
类是键/值对的列表。
Dictionary
类定义的抽象方法如下 -
编号 | 方法 | 描述 |
---|---|---|
1 | Enumeration elements() |
返回字典中包含的值的枚举。 |
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
类已过时,应该实现Map接口以获取键/值存储功能。
示例
// Java Program explaining util.Dictionary class Methods
// put(), elements(), get(), isEmpty(), keys()
// remove(), size()
import java.util.*;
public class DictionaryDemo
{
public static void main(String[] args)
{
// 初始化 Dictionary
Dictionary geek = new Hashtable();
// put() method
geek.put("123", "Yii");
geek.put("456", "Bai");
// elements() method :
for (Enumeration i = geek.elements(); i.hasMoreElements();)
{
System.out.println("Value in Dictionary : " + i.nextElement());
}
// get() method :
System.out.println("Value at key = 6 : " + geek.get("6"));
System.out.println("Value at key = 456 : " + geek.get("123"));
// isEmpty() method :
System.out.println("There is no key-value pair : " + geek.isEmpty());
// keys() method :
for (Enumeration k = geek.keys(); k.hasMoreElements();)
{
System.out.println("Keys in Dictionary : " + k.nextElement());
}
// remove() method :
System.out.println("Remove : " + geek.remove("123"));
System.out.println("Check the value of removed key : " + geek.get("123"));
System.out.println("Size of Dictionary : " + geek.size());
}
}
执行上面示例代码,得到以下结果 -
Value in Dictionary : Yii
Value in Dictionary : Bai
Value at key = 6 : null
Value at key = 456 : Yii
There is no key-value pair : false
Keys in Dictionary : 123
Keys in Dictionary : 456
Remove : Yii
Check the value of removed key : null
Size of Dictionary : 1