java 中MAP的按照进入顺序遍历与无序遍历

public static void main(String[] args) {

Map<String,String> map=new HashMap<String,String>();

map.put("username", "qq");

map.put("passWord", "123");

map.put("userID", "1");

map.put("email", "qq@qq.com");

for(String key:map.keySet()){

System.out.println(key+"\t"+map.get(key));

}

}

输出结果为:

userID 1

username qq

email qq@qq.com

passWord 123

将上述代码改为:

Map<String,String> map=new LinkedHashMap<String,String>();

输出结果为:

username qq

passWord 123

userID 1

email qq@qq.com

HashMap是一个最常用的Map,它根据键的hashCode值存储数据,根据键可以直接获取它的值,具有很快的访问速度。HashMap最多只允许一条记录的键为NULL,允许多条记录的值为NULL。

LinkedHashMap保存了记录的插入顺序,在用Iterator遍历LinkedHashMap时,先得到的记录肯定是先插入的。在遍历的时候会比HashMap慢TreeMap能够把它保存的记录根据键排序,默认是按升序排序,也可以指定排序的比较器。当用Iterator遍历TreeMap时,得到的记录是排过序的。(来自http://www.cnblogs.com/hubingxu/archive/2012/02/21/2361281.html)