java dictionary 类_Java Dictionary类

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

¥ 我要打赏

纠错/补充

收藏

加QQ群啦,易百教程官方技术学习群

注意:建议每个人选自己的技术方向加群,同一个QQ最多限加 3 个群。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值