注意:
键值是唯一的,1个键对应一个值
常用api
打印处字典直接println方法
判断是否存在key值 containsKey()
例子:
基础操作
遍历和取值的方法
下面是虫师java-selenium教得
import java.util.HashMap; import java.util.Iterator;
public class Zidian {
public static void main(String[] args)
{
HashMap<String, String> hm = new HashMap<String, String>();
//添加字典
hm.put("username", "password");
hm.put("Jim","1155689");
hm.put("Jane","1255669"); hm.put("Kevin","1165669");
//测试 key 是否包含 username,返回值为 ture/false 48
System.out.println("===================>");
//获取 key 所对应的 vlaue System.out.println(hm.get("Jim")); System.out.println("===================>");
//获取整个字典数据 System.out.println(hm.entrySet()); System.out.println("===================>");
//循环打印每一对 key=value
Iterator<?> it=hm.entrySet().iterator();
while(it.hasNext())
{
System.out.println(it.next()); }
System.out.println("===================>");
//分别获取 key 的值,和 value 的值。 Iterator<String> it2 = hm.keySet().iterator(); while(it2.hasNext()) {
//获得字典的 key(username)
String username = (String)it2.next();
System.out.println(username);
//获得字典的 value(节点)
String password = hm.get(username);
System.out.println(password);
}
}
}
打印结果:
>>>
true
===================>
1155689
===================>
[Kevin=1165669, Jane=1255669, username=password, Jim=1155689]
===================>
Kevin=1165669
Jane=1255669
username=password
Jim=1155689
49
===================>
Kevin
1165669
Jane
1255669 username password Jim 1155689