java.lang.String无法强制转换为java.util.Map $ Entry

时间:2013-10-29 12:42:40

标签: java

public static void main(String[] args) {
        // TODO Auto-generated method stub
        Map<String,String> map = new HashMap<String,String>();
        Iterator itr = null;
        StringBuffer sb = null;
        Entry entry = null;
        String key = null;
        String val = null;

        map.put("1", "Rakesh");
        map.put("2", "Amal");
        map.put("3", "Nithish");

        itr = map.keySet().iterator();
        sb = new StringBuffer();

        while(itr != null && itr.hasNext()) {
            try {
                entry = (Entry) itr.next();
                key = (String) entry.getKey();
                val = (String) entry.getValue();
                System.out.println(key);
                System.out.println(val);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }


    }






java.lang.ClassCastException: java.lang.String cannot be cast to java.util.Map$Entry
    at com.sixdee.prepaidwork.MapZ.main(MapZ.java:38)
java.lang.ClassCastException: java.lang.String cannot be cast to java.util.Map$Entry
    at com.sixdee.prepaidwork.MapZ.main(MapZ.java:38)
java.lang.ClassCastException: java.lang.String cannot be cast to java.util.Map$Entry
    at com.sixdee.prepaidwork.MapZ.main(MapZ.java:38)

1 个答案:

答案 0 :(得分:10)

itr = map.keySet().iterator();

应该是

itr = map.entrySet().iterator();

...您可能会注意到,如果您在整个计划中正确使用了泛型,则可以itr类型Iterator<Map.Entry<String, String>>entry类型Map.Entry<String, String>