文章目录


代码

存储相同的数据量,对比两个map的存储时间。

package cn.edut.hash;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;

public class Test_mapComparate {
	public static void main(String[] args) {
		System.out.println("\n--TreeMap 数据 存入 HashMap---");
		treeToHash();
		System.out.println("\n--HashMap 数据 存入 TreeMap---");
		hashToTree();
		System.out.println("\n--HashMap 数据 存入 concurrentHashMap---");
		hashToconCurrentHash();
	}
	
	private static void hashToconCurrentHash() {
		//保证排序
		Map<Integer , Character > map = new HashMap<Integer, Character>() ;
		int n = Integer.MAX_VALUE >>> 10  ;
		System.out.println("录入数据量:"+n);
		
		long s = System.currentTimeMillis();
		for (int i = n; i >=0; i--) {
			map.put(i, (char) i);
		}
		long e = System.currentTimeMillis();
		System.out.println("HashMap录入数据...用时:"+(e-s)/1000 +"s"+" size="+map.size());
		
		
		
		s = System.currentTimeMillis();
		map = new ConcurrentHashMap<>(map);
		e = System.currentTimeMillis();
		System.out.println("ConcurrentHashMap录入数据...用时:"+(e-s)/1000 +"s"+" size="+map.size());
	}
	

	private static void hashToTree() {
		//保证排序
		Map<Integer , Character > map = new HashMap<Integer, Character>() ;
		int n = Integer.MAX_VALUE >>> 10  ;
		System.out.println("录入数据量:"+n);
		
		long s = System.currentTimeMillis();
		for (int i = n; i >=0; i--) {
			map.put(i, (char) i);
		}
		long e = System.currentTimeMillis();
		System.out.println("HashMap录入数据...用时:"+(e-s)/1000 +"s"+" size="+map.size());
		
		
		
		s = System.currentTimeMillis();
		map = new TreeMap<>(map);
		e = System.currentTimeMillis();
		System.out.println("TreeMap录入数据...用时:"+(e-s)/1000 +"s"+" size="+map.size());
	}


	private static void treeToHash() {
		//保证排序
		Map<Integer , Character > map = new TreeMap<Integer, Character>() ;
		int n = Integer.MAX_VALUE >>> 10  ;
		System.out.println("录入数据量:"+n);
		
		long s = System.currentTimeMillis();
		for (int i = n; i >=0; i--) {
			map.put(i, (char) i);
		}
		long e = System.currentTimeMillis();
		System.out.println("TreeMap录入数据...用时:"+(e-s)/1000 +"s"+" size="+map.size());
		
		
		
		s = System.currentTimeMillis();
		map = new HashMap<>(map);
		e = System.currentTimeMillis();
		System.out.println("HashMap录入数据...用时:"+(e-s)/1000 +"s"+" size="+map.size());
	}
}


测试结果

存入相同数据,HashMap明显快于TreeMap。

concurrentHashMap用于多线程,这里只考虑单线程,因此性能无法比较。