Map.Entry使您可以方便处理Map 元素,Map接口声明的 entrySet()方法返回一个包含Map 元素的Set。每个set元素都是一个Map.Entry对象。
下表总结了此接口声明的方法-
Sr.No. | Method & Remark |
---|---|
1 | boolean equals(Object obj) 如果obj是其键和值与调用对象的键和值相等的Map.Entry,则返回true。 |
2 | Object getKey() 返回此Map 元素的键。 |
3 | Object getValue() 返回此Map 元素的值。 |
4 | int hashCode() 返回此Map 元素的hashCode。 |
5 | Object setValue(Object v) 将此Map 元素的值设置为 v 。如果 v 不是Map的正确类型,则抛出ClassCastException。如果 v 为null且Map不允许空键,则抛出NullPointerException。如果无法更改Map,则抛出UnsupportedOperationException。 |
以下是显示如何使用 Map.Entry 的示例-
import java.util.*; public class HashMapDemo { public static void main(String args[]) { //创建哈希映射 HashMap hm=new HashMap(); //将元素放入映射 hm.put("Learnfk", new Double(3434.34)); hm.put("Mahnaz", new Double(123.22)); hm.put("Ayan", new Double(1378.00)); hm.put("Daisy", new Double(99.22)); hm.put("Qadir", new Double(-19.08)); //Get a set of the entries Set set=hm.entrySet(); //获取迭代器 Iterator i=set.iterator(); //显示元素 while(i.hasNext()) { Map.Entry me=(Map.Entry)i.next(); System.out.print(me.getKey() + ": "); System.out.println(me.getValue()); } System.out.println(); //将 1000 存入 Learnfk 的账户 double balance=((Double)hm.get("Learnfk")).doubleValue(); hm.put("Learnfk", new Double(balance + 1000)); System.out.println("Learnfk's new balance: " + hm.get("Learnfk")); } }
这将产生以下输出-
Daisy: 99.22 Ayan: 1378.0 Learnfk: 3434.34 Qadir: -19.08 Mahnaz: 123.22 Learnfk's new balance: 4434.34
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)
HarmonyOS快速入门与实战 -〔QCon+案例研习社〕