Java代码
- import java.util.HashMap;
- import java.util.LinkedHashMap;
- import java.util.Map;
- import java.util.TreeMap;
- public class Test {
- public static void main(String[] args) {
- Map tree = new TreeMap();
- Map linked = new LinkedHashMap();
- Map hash = new HashMap();
- System.out.println("tree :"+buildMap(tree));
- System.out.println("link :"+buildMap(linked));
- System.out.println("hash :"+buildMap(hash));
- }
- private static Map buildMap(Map map){
- map.put("0", "a");
- map.put("e", "b");
- map.put("4", "s");
- map.put("3", "c");
- return map;
- }
- }
输出结果:
Java代码
- tree :{0=a, 3=c, 4=s, e=b}
- link :{0=a, e=b, 4=s, 3=c}
- hash :{3=c, 0=a, 4=s, e=b}
由此可见:
HashMap是按照HashCode 排序,莫名其妙的顺序。
TreeMap是按照自身的顺序排序,比如数字的话,按照数字升序,ascII等。
LinkedHashMap是按照先进先出的顺序。