The most common use of map is HashMap, but hashmap elements are not in the order to add, then in addition to the use of HASHMAP, what map interface implementation classes can be used.
There are 2 of them, TreeMap and Linkedhashmap, but to meet our requirements: Save elements in the order of addition, only linkedhashmap.
Look at the code running below.
Package com.lxk.collectionTest;
Import Com.google.common.collect.Maps;
Import Java.util.Map; /** * Test Map for order difference * <p> * Created by LXK on 2017/5/24 */public class Orderedmaptest {public static void M
Ain (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 ());
}
}
}
Then there is the graph of the running results.
As you can see, if you just say orderly, then the hashmap is disorderly, but, to add the order, it is only linkedhashmap.
I finished writing the article, to give myself a little praise, not too much,
But I'm going to order it.
I'll start with a toast, you're free. Everyone is free. Don't be polite ...