Java map集合順序如何同步添加順序
一般使用map用的最多的就是hashmap,但是hashmap里面的元素是不按添加順序的,那么除了使用hashmap外,還有什么map接口的實(shí)現(xiàn)類(lèi)可以用呢?
這里有2個(gè),treeMap和linkedHashMap,但是,要達(dá)到我們的要求:按添加順序保存元素的,就只有LinkedHashMap。
下面看運(yùn)行的代碼。
package com.lxk.collectionTest; import com.google.common.collect.Maps; import java.util.Map; /** * 測(cè)試Map是否有序的區(qū)別 * <p> * Created by lxk on 2017/5/24 */ public class OrderedMapTest { public static void main(String[] args) { Map<String, Integer> hashMap = Maps.newHashMap(); Map<String, Integer> treeMap = Maps.newTreeMap(); Map<String, Integer> linkedHashMap = Maps.newLinkedHashMap(); System.out.println('--------------test hashMap'); testMap(hashMap); System.out.println('--------------test treeMap'); testMap(treeMap); System.out.println('--------------test linkedHashMap'); testMap(linkedHashMap); } private static void testMap(Map<String, Integer> map) { map.put('asd', 1); map.put('2das', 2); map.put('3das', 3); map.put('4das', 4); for (Map.Entry<String, Integer> entry : map.entrySet()) { System.out.println(entry.getKey() + ':' + entry.getValue()); } } }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. PHP設(shè)計(jì)模式中工廠(chǎng)模式深入詳解2. asp中response.write("中文")或者js中文亂碼問(wèn)題3. jsp網(wǎng)頁(yè)實(shí)現(xiàn)貪吃蛇小游戲4. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向5. CSS hack用法案例詳解6. .Net Core和RabbitMQ限制循環(huán)消費(fèi)的方法7. asp(vbs)Rs.Open和Conn.Execute的詳解和區(qū)別及&H0001的說(shuō)明8. 將properties文件的配置設(shè)置為整個(gè)Web應(yīng)用的全局變量實(shí)現(xiàn)方法9. ASP.NET MVC遍歷驗(yàn)證ModelState的錯(cuò)誤信息10. 用css截取字符的幾種方法詳解(css排版隱藏溢出文本)
