注册 登录
编程论坛 JAVA论坛

Java中的HashMap,为什么输出竟然是有序的?

mosquiyan 发布于 2015-11-20 15:52, 1102 次点击
import java.util.*;

public class MapTest {
   
    private String word;
    private String id;
    public MapTest(String id,String word){
        this.id=id;
        this.word=word;
    }
   
    public String GetWord(){
        return word;
    }
   
    public String GetId(){
        return id;
    }
   
    public static void main(String[] args) {
        Map<String,String> map=new HashMap<>();//由HashMap实现的Map对象
        MapTest a1=new MapTest("004","apple");
        MapTest a2=new MapTest("008","banana");
        MapTest a3=new MapTest("003","dog");
        MapTest a4=new MapTest("010","cat");
        MapTest a5=new MapTest("005","hello");
        MapTest a6=new MapTest("006","english");
        MapTest a7=new MapTest("009","math");
        MapTest a8=new MapTest("002","morning");
        MapTest a9=new MapTest("007","good");
        MapTest a10=new MapTest("001","excellent");
        map.put(a1.GetId(),a1.GetWord());
        map.put(a2.GetId(),a2.GetWord());
        map.put(a3.GetId(),a3.GetWord());
        map.put(a4.GetId(),a4.GetWord());
        map.put(a5.GetId(),a5.GetWord());
        map.put(a6.GetId(),a6.GetWord());
        map.put(a7.GetId(),a7.GetWord());
        map.put(a8.GetId(),a8.GetWord());
        map.put(a9.GetId(),a9.GetWord());
        map.put(a10.GetId(),a10.GetWord());
        
        Set<String> set=map.keySet();
        Iterator <String> it=set.iterator();
        System.out.println("HashMap类实现的Map集合,无序");
        while(it.hasNext()){
            String str=(String)it.next();
            String eng=(String)map.get(str);
            System.out.println(str+" "+eng);
        }
    }
}
只有本站会员才能查看附件,请 登录
1 回复
#2
林月儿2015-11-20 17:28
HashMap类实现的Map集合,无序
010 cat
008 banana
009 math
004 apple
005 hello
006 english
007 good
001 excellent
002 morning
003 dog
1