0

I'm trying to initialize a Comparable array using an int to determine initialize the size of the array. However, after I initialize the array, the array is null. If I try and add things to the array, I get a NPE.

Below is some relevant code (I realize it is not type-safe, that's not a concern atm)

public class Heap implements MyHeap{
int capacity;
int size;
Comparable[] heap;

public void Heap(){
    size = 0;
    capacity = 10;
            heap = new Comparable[capacity];
}

public void printHeap(){
    for (int i = 1; i <= size; i++){
        System.out.println(heap[i]);
    }
}

public void insert (Comparable object){
    size++;
    heap[size] = object;
    bubbleUp(size);
}

EDIT: I've changed my code to reflect the suggestion of the first answer. I set the value for the int capacity before I initialize my array using that int, and the array is still null and has null length. I even initialized the array using an int as the parameter as opposed to the variable capacity and I got the same behavior.

1 Answer 1

1

You never initialized the variable capacity used to set the size of the array before using it. Change your code to the following:

public class Heap implements MyHeap{
int capacity;
int size;
Comparable[] heap;

public Heap(){
    size = 0;
    capacity = 10;
    heap = new Comparable[capacity];
}

Edit: I also noticed there's an issue with your insert code. You are using your size counter as an access variable, which won't work because while size can be 1, the first location of the array is 0. Change to the following code. Technically your code would work until you got near the end of the array, when it would really mess up. Also your print code wasn't quite right.

public void printHeap(){
    for (int i = 1; i < capacity; i++){
        if(heap[i] != null) {
            System.out.println(heap[i]);
        }
    }
}

public void insert (Comparable object){
    if(size < capacity) {
        heap[size] = object;
        bubbleUp(size);
        size++;
    }
}
Sign up to request clarification or add additional context in comments.

7 Comments

Welp, I'm getting the same behavior. I even changed the initialization to use an int instead of capacity and I got the same behavior.
I updated my answer to fix a couple more errors I found.
Well this might be a little telling of what's going on, but my program is registering size as greater than capacity...
Are you adding multiple objects to your array? Is this even with the updated insert code?
Yes, it's with the updated insert code. And I am adding multiple objects to the array. I had my test program print the size, and it's zero, but the program never enters the conditional in the insert method
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.