Java-优先级队列显示NullPointerException

Java-优先级队列显示NullPointerException,java,nullpointerexception,Java,Nullpointerexception,我在主类中有一个名为Prims的类和该类类型的优先级队列。在我创建了该类及其构造的实例后,我想将该对象推送到队列中。编译良好,但它显示了运行时错误NullPointerException。代码如下: package mst.prims; import java.util.*; public class Main { /** * Minimum Spanning Tree - Prim's Algorithm * @author K

我在主类中有一个名为Prims的类和该类类型的优先级队列。在我创建了该类及其构造的实例后,我想将该对象推送到队列中。编译良好,但它显示了运行时错误NullPointerException。代码如下:

package mst.prims;

import java.util.*;

    public class Main {

        /**
         * Minimum Spanning Tree - Prim's Algorithm
         * @author Kaidul
         */
        static final int MAX = 100; 

        static class Prims{
            int u, v, cost;
            Prims(int u, int v, int cost){
                this.u = u;
                this.v = v;
                this.cost = cost;
            }
        }

        static PriorityQueue<Prims> q, q1, q2 = new PriorityQueue<Prims>(MAX);

        public static void main(String[] args)  {


            Scanner input = new Scanner(System.in);

            for (int i = 0; i < 7; i++) {
                int u, v, cost;
                u = input.nextInt();
                v = input.nextInt();
                cost = input.nextInt();
                Prims temp = new Prims(u, v, cost);

                q.add(temp);
            }
        }

    }

我是Java新手,无法修复它。

它不应该给出
NullPointerException
,而应该给出
ClassCastException
。因为您的类
Prims
没有实现
可比较的
接口,因此无法推入
优先级队列

您需要实现
Comparable
,并在
嵌套的Prims类中提供
compareTo
方法


请为变量使用有意义的名称
u
v
对我来说似乎很模糊,对它们所代表的内容没有任何意义。

来自
优先级队列的Javadoc:

依赖于自然顺序的优先级队列也不允许插入不可比较的对象(这样做可能会导致ClassCastException)


您必须在
Prims
中实现
Comparable
。如果您打算在集合中使用
Prims
,您还应该使用适合您的对象的实现覆盖
equals()
hashCode()

请显示完整的堆栈跟踪,而堆栈跟踪不需要非常困难的帮助。什么是堆栈跟踪?请解释。我是java新手:(奇怪!当我运行代码时,我得到了java.lang.ClassCastException!您现在只使用了'q'。现在请尝试删除q1、q2,至少对我来说它不会显示空指针异常。但是您必须实现comparable以使用优先级队列`Collections.sort(q,new Comparator(){public int compare(Prims x,Prims y){if(x.cost>y.cost)返回1;if(x.costclass Prims implements Comparable
,对我来说,它给出的是NullPointerException,而不是ClassCastException。异常不会很长呃,我实施的时候就抛出了。
1 2
2 3
Exception in thread "main" java.lang.NullPointerException
    at mst.prims.Main.main(Main.java:36)