【问题标题】:null value during putting value on map将值放在地图上时的空值
【发布时间】:2020-07-18 16:22:31
【问题描述】:

我有一个问题。当我输出我的代码时,我首先得到 Id=null Name=null 入口。问题可能出现在哪里?谢谢。

public class Solution {
    HashMap<Integer, String> map;
    static Integer index;
    static String name;

    public Solution() {
        this.map = new HashMap<>();
        map.put(index, name);
    }

    public static void main(String[] args) throws IOException {
        Solution solution = new Solution();
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        for (int i = 0; i < 10; i++) {
            int index = Integer.parseInt(reader.readLine());
            String name = reader.readLine();
            solution.map.put(index, name);
        }

        for (Map.Entry<Integer, String> pair : solution.map.entrySet()) {
            index = pair.getKey();
            name = pair.getValue();
            System.out.println("Id=" + index + " Name=" + name);
        }
    }
}

这是输入:1 str1 2 str2 3 str3 4 str4 5 str5 6 str6 7 str7 8 str8 9 str9 10 str10

这是输出:

Id=null 名称=null

Id=1 名称=str1

Id=2 名称=str2

Id=3 名称=str3

Id=4 名称=str4

Id=5 名称=str5

Id=6 名称=str6

Id=7 名称=str7

Id=8 名称=str8

Id=9 名称=str9

Id=10 名称=str10

【问题讨论】:

  • 从构造函数中去掉这行代码:map.put(index, name);
  • 当您创建解决方案类的对象时,默认情况下会调用构造函数,并且您在此处编写了 map.put(index, name); 这可能会给出空值。

标签: java


【解决方案1】:
 public Solution() {
        this.map = new HashMap<>();
        map.put(index, name); < ---
    }

注意这一行。您正在将 null 值放入构造函数的映射中。删除此行将解决问题

【讨论】:

    【解决方案2】:

    您在构造函数中添加了 hashmap 值,因此它包含的第一个值为 null。您应该将其更改为:-

    public class Solution {
        HashMap<Integer, String> map;
        static Integer index;
        static String name;
    
        public Solution() {
            this.map = new HashMap<>();
        }
    
        public static void main(String[] args) throws IOException {
            Solution solution = new Solution();
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    
            for (int i = 0; i < 1; i++) {
                int index = Integer.parseInt(reader.readLine());
                String name = reader.readLine();
                solution.map.put(index, name);
            }
    
            for (Map.Entry<Integer, String> pair : solution.map.entrySet()) {
                index = pair.getKey();
                name = pair.getValue();
                System.out.println("Id=" + index + " Name=" + name);
            }
        }
    
    
    }
    

    移除 map.put(index, name);来自解决方案构造函数

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-13
      • 2022-01-09
      • 1970-01-01
      • 2018-01-16
      • 2019-03-22
      • 2023-03-14
      • 1970-01-01
      相关资源
      最近更新 更多