java problem Exception in thread \"main\" java.lang.NullPointerException at Prio
ID: 3912403 • Letter: J
Question
java problem
Exception in thread "main" java.lang.NullPointerException
at PriorityQueue.reverseHeapify(PriorityQueue.java:63)
at PriorityQueue.enqueue(PriorityQueue.java:30)
MY CODE:
public class PriorityQueue implements Queue
{
private Job[] heap;
private int tail;
/**
* The constructor creates an empty array for the heap and sets the tail to 0.
*/
public PriorityQueue()
{
heap = new Job[10];
tail = 0;
}
public boolean isEmpty()
{
if (tail == 0)
return true;
return false;
}
public void enqueue(Job job)
{
if (tail >= heap.length)
resize();
heap[tail] = job;
tail++;
reverseHeapify(tail);
}
public Job dequeue()
{
if(isEmpty())
return null;
Job> tail--;
heap[0] = heap[tail];
heap[tail]=null;
heapify(0);
return oneHeap;
}
public void clear()
{
heap = null;
tail = 0;
}
private void resize()
{
Job[]newHeap = new Job[tail*2];
for(int i =0;i<heap.length;i++){
newHeap[i]=heap[i];
}
heap = newHeap;
}
private void reverseHeapify(int i)
{
while(heap[parent(i)].getOwner() < heap[i].getOwner()){
swap(i, parent(i));
}
}
Explanation / Answer
Hi Sir, the issue is because of 2 possible reasons:-
1. heap[parent(i)].getOwner() - Here heap[parent(i)] is null and from this null we are trying to fetch getOwner, so it will throw NullPointerException. Better debug this statement:-
System.out.println(heap[parent(i)].getOwner()); // check if this is printing any value or is null
2. heap[i].getOwner():- The heap[i] is null and from this null we are trying to fetch getOwner, so it will throw NullPointerException. Better debug this statement:-
System.out.println(heap[i].getOwner()); // check if this is printing any value or is null
So, the NullPointer Exception is coming because of either of the 2 mentioned conditions is null from which we are trying to fetch getOwner() record via the function call. Once we debug these values, we can investigate furthur as to what i value needs to be passed so that its not null.
Please let me know in case of any clarifications required. Thanks!
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.