简体   繁体   中英

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

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)
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 itr type Iterator<Map.Entry<String, String>> and entry type Map.Entry<String, String> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM