大家都知道map中的key是一个set集合,但是我们在自己把元素put进map,输出map集合的时候里面的key元素并不是按我们插进去的顺序来输出的。有没有什么办法输出按插进去的顺序输出,简单来说就是把map里key集合set类型换成list类型呢?
TreeMap的顺序是自然顺序(如整数从小到大),也可以指定比较函数。但不是插入的顺序。
用LinkedHashMap吧。它内部有一个链表,保持插入的顺序。迭代的时候,也是按照插入顺序迭代,而且迭代比HashMap快。
使用TreeMap
[code="java"]import java.util.*;
class TreeMapDemo {
public static void main(String args[]) {
// Create a tree map
TreeMap tm = new TreeMap();
// Put elements to the map
tm.put("John Doe", new Double(3434.34));
tm.put("Tom Smith", new Double(123.22));
tm.put("Jane Baker", new Double(1378.00));
tm.put("Todd Hall", new Double(99.22));
tm.put("Ralph Smith", new Double(-19.08));
// Get a set of the entries
Set set = tm.entrySet();
// Get an iterator
Iterator i = set.iterator();
// Display elements
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
// Deposit 1000 into John Doe's account
double balance = ((Double)tm.get("John Doe")).doubleValue();
tm.put("John Doe", new Double(balance + 1000));
System.out.println("John Doe's new balance: " +
tm.get("John Doe"));
}
}[/code]
使用LinkedHashMap和TreeMap都行吧。。
用LinkedHashMap就可以了。
HashMap并不能保证按插入的顺序,LinkedHashMap是在HashMap的基础上维护了一个链表,保存你的插入顺序,所以使用LinkedHashMap可以达到楼主想要的效果! :D
显然要使用LinkedHashMap类