Java之HashMap用法

源码:

 package test_demo;

 import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random; /*
* @desc HashMap测试程序
*/ public class HashMapDemo {
private static void testHashMapAPIs() {
// 初始化随机种子
Random r = new Random();
// 新建HashMap
HashMap map = new HashMap();
// 添加操作
map.put("one", r.nextInt(10));
map.put("two", r.nextInt(10));
map.put("three", r.nextInt(10));
// 打印出map
System.out.println("map:" + map);
// 通过Iterator遍历key-value
Iterator iter = map.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
System.out.println("next : " + entry.getKey() + ":" + entry.getValue());
}
// HashMap的键值对个数
System.out.println("size:" + map.size());
// containsKey(Object key) :是否包含键key
System.out.println("contains key two : " + map.containsKey("two"));
System.out.println("contains key five : " + map.containsKey("five"));
// containsValue(Object value) :是否包含值value
System.out.println("contains value 0 : " + map.containsValue(new Integer(0)));
// remove(Object key) : 删除键key对应的键值对
map.remove("three");
System.out.println("删除three");
System.out.println("map:" + map);
// clear() : 清空HashMap
map.clear();
System.out.println("清空HashMap");
// isEmpty() : HashMap是否为空
System.out.println((map.isEmpty() ? "map is empty" : "map is not empty"));
} public static void main(String[] args) {
testHashMapAPIs();
}
}

执行结果:

map:{one=1, two=9, three=2}
next : one:1
next : two:9
next : three:2
size:3
contains key two : true
contains key five : false
contains value 0 : false
删除three
map:{one=1, two=9}
清空HashMap
map is empty

  

上一篇:CentOS 7.x设置自定义开机启动,添加自定义系统服务


下一篇:java集合类——Stack栈类与Queue队列