Key有序的Map

LinkedHashMap的Key会按照插入顺序排列,HashMap的key是无序的。

测试用例:

public void testMap()
    {
    	
    	// 测试key有序的map, key按插入顺序排列
    	System.out.println("-------------------------------Linked Map-----------------------------------");
    	Map linkmap = new LinkedHashMap();
    	linkmap.put("王五", "12");
    	linkmap.put("张小龙", "3");
    	linkmap.put("李四", "24");
    	linkmap.put("张三", "23");
    	Iterator linkMapIt = linkmap.keySet().iterator();
    	while(linkMapIt.hasNext()) {
    		String key = linkMapIt.next();
    		System.out.println(key);
    	}
    	
    	// 测试HashMap的key无序
    	System.out.println("-------------------------------Hash Map-----------------------------------");
    	Map hashMap = new HashMap();
    	hashMap.put("王五", "12");
    	hashMap.put("张小龙", "3");
    	hashMap.put("李四", "24");
    	hashMap.put("张三", "23");
    	Iterator hashMapIt = hashMap.keySet().iterator();
    	while(hashMapIt.hasNext()) {
    		String key = hashMapIt.next();
    		System.out.println(key);
    	}
    }


你可能感兴趣的:(java)