【问题标题】:NullPointerException in Queue队列中的 NullPointerException
【发布时间】:2011-12-18 07:52:10
【问题描述】:

我实现了一些涉及队列的代码,在运行它时我得到一个 NullPointerException。请帮助我修复它。我只是编写该代码的较短形式。

import java.util.*;
class ex
{
public static void main(String args[])throws IOException
{

    Scanner in=new Scanner(System.in);
    int i;
    String s;
    int n=in.nextInt();

    Queue<Integer> q=null;
    for(i=0;i<n;i++)
    {
        q.add(i);//I get the error in this line
    }
    System.out.println(q.size());
} 
}

【问题讨论】:

    标签: java queue


    【解决方案1】:

    这是因为qnull。你需要先用一些东西来初始化它,然后才能使用它,例如:

     Queue<Integer> q = new AbstractQueue<Integer>();
    

    有关详细信息和示例,请参阅:

    【讨论】:

      【解决方案2】:

      你需要初始化q

      Queue<Integer> q = new AbstractQueue<Integer>();
      

      【讨论】:

        【解决方案3】:
        Queue<Integer> q=null;
        ...
        q.add(i);//I get the error in this line
        

        您的Queue 引用是null,因此您在尝试访问它时会得到一个NullPointerException。在使用它之前,q 必须指向一些有效的东西,例如:

        Queue<Integer> q = new Queue<Integer>();
        

        【讨论】:

          【解决方案4】:

          你得到一个 NPE,因为 qnull

          你必须先创建一个对象才能使用它,例如:

          Queue<Integer> q = new LinkedList<Integer>();
          

          在这里,我选择了LinkedList 作为实现Queue 接口的类。还有很多其他的:请参阅Queue javadoc 的“所有已知的实现类”部分。

          【讨论】:

            【解决方案5】:
            Queue<Integer> q = null;
            

            嗯...那是null 和:

             q.add(i);
            

            您正在尝试使用它。因此,例外。

            您必须实例化对象才能拥有一个可以使用的对象:

            Queue<Integer> q = new Queue<Integer>();
            

            如果这不是一个简单的错字/疏忽,您可能希望从 Oracle 提供的 Java 教程的开头开始,或者在处理更复杂的问题之前获得一本“学习 Java”类型的书。

            【讨论】:

              【解决方案6】:

              你必须先初始化队列:

              Queue<Integer> q=null;
              

              应该是:

              Queue<Integer> q = new Queue<Integer>();
              

              错误的原因是您试图将值添加到 q。 q 仅设置为 Queue&lt;Integer&gt; 类型,而不是对该类型本身的对象的引用。

              【讨论】:

              • 你不能实例化Queue,因为这个类是抽象的
              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2020-06-24
              • 2012-01-13
              相关资源
              最近更新 更多