java.lang.String 不能转换为 java.util.Map$Entry

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19658546/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 19:12:37  来源:igfitidea点击:

java.lang.String cannot be cast to java.util.Map$Entry

java

提问by

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)

回答by Louis Wasserman

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

should be

应该

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

...as you would have noticed if you'd used generics properly throughout your program, by giving itrtype Iterator<Map.Entry<String, String>>and entrytype Map.Entry<String, String>.

...正如您所注意到的,如果您在整个程序中正确使用泛型,通过提供itrtypeIterator<Map.Entry<String, String>>entrytype Map.Entry<String, String>