java array nullpointer

2019-09-16 05:47发布

问题:

I'm trying to find minimum of an array. The array contain Nodes - a node contains of an element E and a priority int. Im want to find the Node in the array with the smallest priority.

@Override
public E min() {
    Node temp = S[0];
    for(int i = 1; i<S.length; i++){
        int prio= S[i].getPrioritet();   <-- nullpointer excp.
        if(prio<temp.getPrioritet()){
            temp = S[i];
        }
    }
    return temp.getElement();

But i get an nullpointer exception when i try to use it. Does anybody know what im doing wrong?

Here is my test:

PrioritetArraySorteret<String> p = new PrioritetArraySorteret<String>();

    p.insert(1, "Hello");
    p.insert(3, "Hi");
    p.insert(4, "Hawdy");
    System.out.println(p.min());

}

回答1:

It simply means that the element at one of the indexes of array S is null. Maybe you're initialized the array at a size n but filled in less than n positions.

Altering like this will probably fix it:

for(int i = 1; i<S.length; i++){
    if(S[i] != null) {
        int prio= S[i].getPrioritet();   <-- nullpointer excp.
        if(prio<temp.getPrioritet()){
            temp = S[i];
        }
     }
}

That said, you might be reinventing the wheel here a bit. Using a simple ArrayList parameterized with some type that you define which encapsulates a value and priority would do. You could then have that type implement Comparable with a compareTo method that uses the priority, or write a Comparator to use for finding the minimum:

List<YourType<String>> list = new ArrayList<YourType<String>>();
Collections.min(list);

Or, if you're using a custom Comparator:

Collections.min(list, yourComparator);

-- edited for min instead of sort. Sorry.



回答2:

start with i=0 as the array is indexed

for(int i = 0; i<S.length; i++){
    int prio= S[i].getPrioritet();   <-- nullpointer excp.
    if(prio<temp.getPrioritet()){
        temp = S[i];
    }
}


回答3:

The array S has not been initialized or one/more elements has been initialized.