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)
答案 0 :(得分:10)
itr = map.keySet().iterator();
应该是
itr = map.entrySet().iterator();
...您可能会注意到,如果您在整个计划中正确使用了泛型,则可以itr
类型Iterator<Map.Entry<String, String>>
和entry
类型Map.Entry<String, String>
。