本文介紹了放入java HashMap時如何避免重新排序項目的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我正在創建一個新地圖并將字符串推入其中(沒什么大不了的)-但我注意到隨著地圖的增長,字符串正在重新排序.是否可以停止這種重新排序,以便地圖中的項目保留放置時的順序?
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());
}
推薦答案
如果您關心訂單,可以使用 SortedMap
.實現接口的實際類(至少在大多數情況下)是 樹圖
.或者,LinkedHashMap
也維護它的順序,同時仍然使用基于哈希表的容器.
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.
這篇關于放入java HashMap時如何避免重新排序項目的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!