import java.util.*;
public class NewHashTest
{
public static void main(String[] args)
{
HashMap hash = new HashMap();
Emp emp1 = new Emp("laoda","111",123f);
Emp emp2 = new Emp("laoer","222",234f);
Emp emp3 = new Emp("laosan","333",5466f);
hash.put(111,emp1);
hash.put(222,emp2);
hash.put(333,emp3);
if(hash.containsKey(111))
{
Emp em = (Emp)hash.get(111);
em.info();//可以正常顯示
}
Iterator iter = hash.keySet().iterator();
while(iter.hasNext())
{
String key = iter.next().toString();
Emp ems = (Emp)hash.get(key);
ems.info();//這裡會報錯
}
}
}
class Emp
{
String name;
String number;
float slary;
public void info()
{
System.out.println("名字叫:"+name);
System.out.println("編號為:"+number);
System.out.println("薪水是:"+slary);
}
public Emp(String name,String number,float slary)
{
this.name = name;
this.number = number;
this.slary = slary;
}
}
會在ems.info();一行報一個Exception in thread "main" java.lang.NullPointerException的錯誤,是不是傳入的KEY類型有問題,還是什麼別的問題,求指點。
map設置的鍵值對的時候鍵 hash.put(111,emp1) 111為int類型,而遍歷的時候確
String key = iter.next().toString();
使用String類型作為查找的key,當然就會是null了。
可將111 222 改成字符