0

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
  • 1
    for(int i = 1; i<S.length; i++) --> i starts from 1? How much is S.length? In this case it seems S[i] is null.... Commented Nov 4, 2011 at 10:17

3 Answers 3

1

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
  • No because i compare the other elements in the array with the first element in the array --> Node temp = S[0]; Commented Nov 4, 2011 at 10:44
  • This isn't actually solving the problem, and the index had to start at 1 to start comparing from the second element since the first was used as a primer for the minimum. Commented Nov 4, 2011 at 11:25
  • true but it wouldn't make any difference to the result and is a simple solution to what to do when there is only one item in the array Commented Nov 4, 2011 at 11:40
0

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.

0

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

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.