A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 章闽 中级黑马   /  2012-10-15 21:38  /  1556 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

import java.util.*;
import java.lang.*;

public class PolMsg {     
Police pol1 = new Police(23,"zhang1");
Police pol2 = new Police(24,"zhang2");
Police pol3 = new Police(24,"zhang3");
Police pol4 = new Police(24,"zhang4");
Police pol5 = new Police(24,"zhang5");
public void addPol3(){
  try{
   HashMap<Integer,Police> col1 = new HashMap<Integer,Police>();
   col1.put(new Integer(1),pol1);
   col1.put(new Integer(2),pol2);
   col1.put(new Integer(3),pol3);
   col1.put(new Integer(4),pol4);
   col1.put(new Integer(5),pol5);
   for(Iterator i = col1.keySet().iterator();i.hasNext();){
    Police col = (Police) i.next();
    System.out.println(col.getName()+col.getAge());
   }
   System.out.println();
  }catch(ClassCastException e){
   e.printStackTrace();
  }
  
}

public static void main(String[] args) {
  PolMsg p1 = new PolMsg();
  //p1.addPol1();
  //p1.addPol2();
  p1.addPol3();
}
}
请问为什么会抛异常呢?望赐教

评分

参与人数 1技术分 +1 收起 理由
韩军博 + 1 很给力!

查看全部评分

2 个回复

倒序浏览
这句Iterator i = col1.keySet().iterator(),得到的遍历对象是 Integer的,无法得到police对象。

应该这样:
  1. for(Iterator i = col1.keySet().iterator();i.hasNext();){
  2.                    Integer x = (Integer) i.next();
  3.                    System.out.println(col1.get(x).getName()+col1.get(x).getAge());
  4.            }
复制代码
先得到键,再通过map得到值,再由值获得属性。
回复 使用道具 举报
import java.util.*;

public class PolMsg {     
public static void main(String[] args) {
    PolMsg p1 = new PolMsg();
    // p1.addPol1();
    // p1.addPol2();
    p1.addPol3();
  }
Police pol1 = new Police(23,"zhang1");
Police pol2 = new Police(24,"zhang2");
Police pol3 = new Police(24,"zhang3");
Police pol4 = new Police(24,"zhang4");
Police pol5 = new Police(24,"zhang5");

public void addPol3(){
   try{
    HashMap<Integer,Police> col1 = new HashMap<Integer,Police>();
    col1.put(new Integer(1),pol1);
    col1.put(new Integer(2),pol2);
    col1.put(new Integer(3),pol3);
    col1.put(new Integer(4),pol4);
    col1.put(new Integer(5),pol5);
    for(Iterator<Integer> i = col1.keySet().iterator();i.hasNext();){
     Integer key = i.next();    //红色标注为代码的改动,你的代码这个地方会抛格式转化异常
     Police col = col1.get(key);
     System.out.println(col.getName()+"   "+col.getAge());
    }
    System.out.println();
   }catch(ClassCastException e){
    e.printStackTrace();
   }
   
}
}
class Police{
private int age;
private String name;
public Police(int age, String name) {
  super();
  this.age = age;
  this.name = name;
}
public int getAge() {
  return age;
}
public void setAge(int age) {
  this.age = age;
}
public String getName() {
  return name;
}
public void setName(String name) {
  this.name = name;
}

}
运行结果如下:

1.jpg (11.3 KB, 下载次数: 16)

运行结果

运行结果

评分

参与人数 1技术分 +1 收起 理由
韩军博 + 1 很给力!

查看全部评分

回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马