Hashmap(类似字典的东西)

注意:

键值是唯一的,1个键对应一个值

 

常用api

 

 打印处字典直接println方法

判断是否存在key值     containsKey() 

 

例子:

 

基础操作

https://ke.qq.com/webcourse/index.html#cid=434021&term_id=100518216&taid=3776526089101157&vid=5285890793215652529

遍历和取值的方法

https://ke.qq.com/webcourse/index.html#cid=434021&term_id=100518216&taid=3776530384068453&vid=5285890793135617174

 

下面是虫师java-selenium教得

package com.java.base;

 

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

《Selenium2 Java 自动化测试实战》 System.out.println(hm.containsKey("username"));

 

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

《Selenium2 Java 自动化测试实战》

 

===================> Kevin
1165669
Jane

1255669
username
password
Jim
1155689

 

 

 

 

2022-9

循环取键和值

https://www.runoob.com/java/java-string-replace.html

// 引入 HashMap 类      
import java.util.HashMap;

public class RunoobTest {
    public static void main(String[] args) {
        // 创建 HashMap 对象 Sites
        HashMap<Integer, String> Sites = new HashMap<Integer, String>();
        // 添加键值对
        Sites.put(1, "Google");
        Sites.put(2, "Runoob");
        Sites.put(3, "Taobao");
        Sites.put(4, "Zhihu");
        // 输出 key 和 value
        for (Integer i : Sites.keySet()) {
            System.out.println("key: " + i + " value: " + Sites.get(i));
        }
        // 返回所有 value 值
        for(String value: Sites.values()) {
          // 输出每一个value
          System.out.print(value + ", ");
        }
    }
}

 

posted @ 2019-11-24 14:35  凯宾斯基  阅读(534)  评论(2编辑  收藏  举报