黑马程序员技术交流社区
标题:
hashmap里的小问题
[打印本页]
作者:
章闽
时间:
2012-10-15 21:38
标题:
hashmap里的小问题
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();
}
}
请问为什么会抛异常呢?望赐教
作者:
张 涛
时间:
2012-10-15 22:05
这句Iterator i = col1.keySet().iterator(),得到的遍历对象是 Integer的,无法得到police对象。
应该这样:
for(Iterator i = col1.keySet().iterator();i.hasNext();){
Integer x = (Integer) i.next();
System.out.println(col1.get(x).getName()+col1.get(x).getAge());
}
复制代码
先得到键,再通过map得到值,再由值获得属性。
作者:
汪小照
时间:
2012-10-15 22:23
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, 下载次数: 21)
下载附件
2012-10-15 22:22 上传
运行结果
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2