有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

字典在Java中使用映射条目时出错

这是我写的代码

import java.util.*;

public class Program
{
    public static void main(String[] args) {

        Map <Integer,String> map = new HashMap <Integer,String>();  

        map.put(100,"Amit");  
        map.put(101,"Vijay");  
        map.put(102,"Rahul");

        Set set = map.entrySet();
        Iterator i = set.iterator();
        Map.Entry hello;

        while (i.hasNext()) {
            hello = (Map.Entry) i.next();
        }

        System.out.println (hello.getValue());
    }
}

我希望输出为“Rahul”,但是在println语句中得到一个错误,变量hello可能尚未初始化


共 (4) 个答案

  1. # 1 楼答案

    出现此错误the variable _hello_ might not have been initialized的原因是变量hello从未初始化,可能存在映射为空的情况,在这种情况下,它将永远不会进入while循环

    如果您真的想深入研究这个问题,Java语言规范的一整章都是专门讨论Definite Assignment问题的。例如:

    the rules do not accept the variation:

    void flow(boolean flag) {
      int k;
      if (flag)
        k = 3;
      if (!flag)
        k = 4;
    System.out.println(k);  // k is not "definitely assigned" before here
    }
    

    and so compiling this program must cause a compile-time error to occur.

    同样,在您的情况下,变量hello从未初始化。将其初始化为null将解决您的问题

  2. # 2 楼答案

    局部变量在使用前必须初始化
    要解决此问题,请将其设置为null。如果只在while语句中使用变量,还可以在while语句中声明该变量

    此外,与原始类型相比,您应该更喜欢泛型类型
    它可以像您所做的那样防止不安全的强制转换,并使您的代码更加健壮

    Map.Entry<Integer,String> entry = null;
    while (i.hasNext()) {
       entry = i.next();  
        ...
    }
    
  3. # 3 楼答案

    您的代码应该如下所示

    import java.util.*;
    
    public class Program
    {
        public static void main(String[] args) {
    
            Map <Integer,String> map = new HashMap <Integer,String>();
    
            map.put(100,"Amit");
            map.put(101,"Vijay");
            map.put(102,"Rahul");
    
            Set set = map.entrySet();
            Iterator i = set.iterator();
            Map.Entry hello = null;
    
            while (i.hasNext()) {
                hello = (Map.Entry) i.next();
                System.out.println (hello.getValue());
            }
    
        }
    }
    

    现在您将看到地图上的所有名称。:)

  4. # 4 楼答案

    如果未输入循环,变量hello将不会初始化,这就是编译器中出现错误的原因,因此更改行:

    Map.Entry hello;
    

    Map.Entry hello = null;