Java map集合順序如何同步添加順序
一般使用map用的最多的就是hashmap,但是hashmap里面的元素是不按添加順序的,那么除了使用hashmap外,還有什么map接口的實(shí)現(xiàn)類可以用呢?
這里有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. 使用vue-cli創(chuàng)建項(xiàng)目并webpack打包的操作方法2. 在vue中獲取wangeditor的html和text的操作3. Python用K-means聚類算法進(jìn)行客戶分群的實(shí)現(xiàn)4. python mysql 字段與關(guān)鍵字沖突的解決方式5. python編寫五子棋游戲6. Java xml數(shù)據(jù)格式返回實(shí)現(xiàn)操作7. 解決Android Studio Design界面不顯示layout控件的問(wèn)題8. vue style width a href動(dòng)態(tài)拼接問(wèn)題的解決9. Java源碼解析之接口List10. python讀取中文路徑時(shí)出錯(cuò)(2種解決方案)
