2 jiandanai667 jiandanai667 于 2013.07.28 00:45 提问

Java中遇到的一个异常Exception in thread "main" java.lang.NullPointerException

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类型有问题,还是什么别的问题,求指点。

1个回答

zhangxiaofei13
zhangxiaofei13   2013.07.28 16:13
已采纳

map设置的键值对的时候键 hash.put(111,emp1) 111为int类型,而遍历的时候确
String key = iter.next().toString();
使用String类型作为查找的key,当然就会是null了。

可将111 222 改成字符

Csdn user default icon
上传中...
上传图片
插入图片