0
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)
2
  • 2
    If you avoid using the raw Entry and Iterator types, you'll get the appropriate error at compile time... Commented Oct 29, 2013 at 12:43
  • 1
    BTW, you can really simplify the iteration, by using enhanced for loop. And also, Java is not C. You don't need to declare the variables all at one place. You can declare them as you need them. Commented Oct 29, 2013 at 12:45

1 Answer 1

10
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>.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.