java.util.Map下集合学习总结---备忘

luozhangwen luozhangwen 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区

package com.lzw.test;

import java.util.Collections;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class MapTest
{
/*
Map小结:
预置条件:多个线程操作Map

1.使用new HashMap会抛出java.util.ConcurrentModificationException 能够使用null做键与值

2.使用Collections.synchronizedMap(new HashMap<String, String>()),在迭代的时候需要同步.如下:
synchronized (map){
for (Entry<String, String> entry : map.entrySet()){
System.out.println(entry.getKey() + " " + entry.getValue());
}
}

3.JDK1.5新特性, ConcurrentHashMap类遵守与 Hashtable 相同的功能规范,线程同步,不允许使用null作为键值等.
*/

/*
预置条件:数据为1000000
HashMap使用时间:1844
Collections.synchronizedMap使用时间:1813
ConcurrentHashMap使用时间:1437
Hashtable使用时间:749
*/

public static void main(String[] args)
{

// Map<Integer, Integer> map1 =Collections.synchronizedMap(new HashMap<Integer, Integer>());
// Map<Integer, Integer> map2 =new HashMap<Integer, Integer>();
// Map<Integer, Integer> map3 =new ConcurrentHashMap<Integer, Integer>();
// Map<Integer, Integer> map4 =new Hashtable<Integer, Integer>();
// //注意:是用new的时候能不获得实例句柄, 就最好不去获得. 因为数据量太大会造成堆栈溢出..
// MapTest.countTime(map1, "map1");
// MapTest.countTime(map2, "map2");
// MapTest.countTime(map3, "map3");
// MapTest.countTime(map4, "map4");

MapTest.countTime(Collections.synchronizedMap(new HashMap<Integer, Integer>()), "Collections.synchronizedMap");
MapTest.countTime(new HashMap<Integer, Integer>(), "HashMap");
MapTest.countTime(new ConcurrentHashMap<Integer, Integer>(), "ConcurrentHashMap");
MapTest.countTime(new Hashtable<Integer, Integer>(), "Hashtable");

}

public static void countTime(Map<Integer, Integer> map, String mapName)
{
long start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++)
{
map.put(i, i);
}
System.out.println(mapName + "使用时间:" + (System.currentTimeMillis() - start));
map = null;
System.gc();
}
}

...全文

相关推荐

评论 2
收藏 已收藏
分享
返回顶部
luozhangwen
非技术区 23,404 成员 70,506 内容