转载

Java自动化测试(HashSet和HashMap 7)

HashSet

特点:存储和取出顺序不一样,无索引,不可重复

package com.zhongxin.day08;

import java.util.HashSet;

public class HashSetDemo {
    public static void main(String[] args) {
        HashSet<String> set = new HashSet<>();
        set.add("测试");
        set.add("测试");
        set.add("a");
        set.add("b");
        set.add("c");
        set.add("1");
        set.add("2");
        set.add("3");
        System.out.println(set); // [a, 1, b, 2, c, 3, 测试]
    }
}

取出的方法

打印

System.out.println(set);

增强for

for (String e : set) {
    System.out.println(e);
}

迭代器

Iterator<String> it = set.iterator();
while (it.hasNext()) {
    String s = it.next();
    System.out.println(s);
}

HashMap

定义

import java.util.HashMap;

HashMap<String, Integer> map = new HashMap<>();
package com.zhongxin.day08;

import java.util.HashMap;

public class HashMapDemo {
    public static void main(String[] args) {
        HashMap<String, Integer> map = new HashMap<>();
        map.put("id", 100);
        map.put("age", 18);
        map.put("score", 60);
        System.out.println(map);//{score=60, id=100, age=18}
        map.put("score", 80);
        System.out.println(map);//{score=80, id=100, age=18}
    }
}

取出某个

int id = map.get("id");
System.out.println(id);//100
System.out.println(map.get("id1"));//null

长度

System.out.println(map.size());//3

删除

map.remove("id");
System.out.println(map);// {score=80, age=18}

获取所有的key

import java.util.Set;

Set<String> set = map.keySet();
System.out.println(set);// [score, age]

获取所有的值

import java.util.Collection;

Collection<Integer> values = map.values();
System.out.println(values);//[80, 18]

判断key是否存在

System.out.println(map.containsKey("score"));// true

遍历输出

方法一

Set<String> set_key = map.keySet();
for (String key : set_key) {
    int value = map.get(key);
    System.out.println(key + "=" + value);
}
//score=80
//age=18

方法二

Set<Map.Entry<String, Integer>> entrySet = map.entrySet();
for (Map.Entry<String, Integer> entry : entrySet) {
    System.out.println(entry.getKey() + "=" + entry.getValue());
}
原文  http://mp.weixin.qq.com/s?__biz=MzU5NTI3NDcxOA==&mid=2247484688&idx=1&sn=ef18cd9d7aceb824cb3ecf8eccbe1a21
正文到此结束
Loading...