vvcgp
moeC
2017-01-13 07:41

HashMap输出空指针错误的问题

  • java
  • hashmap
 import java.util.*;

public class Map集合 {
    public static void main(String[] args) {


        HashMap hm = new HashMap(); // 创建一个没有指定类型的Map集合
        Student s1 = new Student("广平", "男");
        Student s2 = new Student("庆阳", "男");
        // Student s3=new Student("心怡","女");
        hm.put("1", s1);
        hm.put("2", s2);
        hm.put("3", (new Student("心怡", "女")));
        hm.put("4", "年龄18");
        hm.put("5", 50);
        // 查找学生编号是001的学生
        // 因为hm.get("001")反回的是Object所以加上强转
        Student s = (Student) hm.get("001");
        System.out.println(s.toString());
        System.out.println("放入不同数据类型的hm集合的元素:" );
        System.out.println(hm);

    }
}

class Student {
    String name;
    String sex;

    public Student(String n, String s) {
        name = n;
        sex = s;
    }

    public String toString() {
        return ("姓名:" + name + " " + "性别:" + sex + " ");
    }

}

上述代码为什么会报空指针错误?但是我把几个put方法改成下述样子就可以:

        hm.put("001", s1);
        hm.put("002", s2);
        hm.put("003", (new Student("心怡", "女")));
        hm.put("004", "年龄18");
        hm.put("005", 50);
  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

3条回答

为你推荐