問(wèn)題描述
我正在創(chuàng)建一個(gè)新地圖并將字符串推入其中(沒什么大不了的)-但我注意到隨著地圖的增長(zhǎng),字符串正在重新排序.是否可以停止這種重新排序,以便地圖中的項(xiàng)目保留放置時(shí)的順序?
I'm creating a new Map and pushing strings into it (no big deal) -but I've noticed that the strings are being re-ordered as the map grows. Is it possible to stop this re-ordering that occurs so the items in the map retain the order the were put in with?
Map<String,String> x = new HashMap<String, String>();
x.put("a","b");
x.put("a","c");
x.put("a","d");
x.put("1","2");
x.put("1","3");
x.put("1","4");
//this shows them out of order sadly...
for (Map.Entry<String, String> entry : x.entrySet()) {
System.out.println("IN THIS ORDER ... " + entry.getValue());
}
推薦答案
如果您關(guān)心訂單,可以使用 SortedMap
.實(shí)現(xiàn)接口的實(shí)際類(至少在大多數(shù)情況下)是 樹圖
.或者,LinkedHashMap
也維護(hù)它的順序,同時(shí)仍然使用基于哈希表的容器.
If you care about order, you can use a SortedMap
. The actual class which implements the interface (at least for most scenarios) is a TreeMap
. Alternatively, LinkedHashMap
also maintains its order, while still utilizing a hashtable-based container.
這篇關(guān)于放入java HashMap時(shí)如何避免重新排序項(xiàng)目的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!