I have a class inside the main class named Prims and a priority queue of the class type.After I created an instance of the class with its construct, I want to push the object into the queue.Compiled well, But it shows run-time error with NullPointerException .Here is the code:
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);
}
}
}
Error :
1 2
2 3
Exception in thread "main" java.lang.NullPointerException
at mst.prims.Main.main(Main.java:36)
I am new in Java and can’t fix it.
From the Javadoc for
PriorityQueue:You must implement
ComparableinPrims. If you intend to usePrimsin collections you should also overrideequals()andhashCode()with implementations appropriate for your object.