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

luozhangwen 2010-07-29 09:20:14

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();
}
}

...全文
520 2 打赏 收藏 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
maxch1225 2010-09-17
  • 打赏
  • 举报
回复
学习一下!
luozhangwen 2010-07-29
  • 打赏
  • 举报
回复
这个map =null; 与System.gc(); 需要去掉.

23,404

社区成员

发帖
与我相关
我的任务
社区描述
Java 非技术区
社区管理员
  • 非技术区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧