0

I am getting a null pointer exception when i run this bubble sort and i'm not sure why, can someone please explain the problem?

for(int i = 1; i < clipArray.length; i++) {
    for(int j = 0; j < clipArray.length - 1; j++) {
        if(((clipArray[j].getSurname()).compareToIgnoreCase((clipArray[j+1].getSurname()))) > 0) {
            Clip temp = clipArray[j];
            clipArray[j] = clipArray[j+1];
            clipArray[j+1] = temp;
        }
    }
}
for(int g = 0; g < clipArray.length; g++) {
    System.out.println(clipArray[g].getSurname());
}

I am trying to print out the surnames of objects in an array.

I tested it with 2 elements in the array, and all other elements are null.

The exception happens at the if statement on the third line.

1
  • 2
    "I tested it with 2 elements in the array, and all other elements are null." You are getting a null pointer exception. Ponder those two facts for a bit.
    – Kevin
    Commented Oct 25, 2013 at 3:27

3 Answers 3

0

The issue here is that you are still accessing those null elements in the sort. I'm assuming your array is longer than just 2 elements. Instead, I would include another condition in that if statement for if the object is null.

if(clipArray[i] != null && clipArray[j] != null && ...Rest of your statements here)

Or keep track of how many elements are there beforehand. So have an int that knows that there are only 2 elements. And loop until you hit that instead.

Java actually provides a way for you to do this via an ArrayList. Documentation can be found here. Instead of looping through length, just call .size().

0
0

Shorten clipArray so the length matches the number of non-null elements. Then you won't end up trying to read in a null element. If you want to grow your array as you read in surnames, you can use an instance of the ArrayList class from the Java Collections API.

Also, not sure if you care, but slightly more efficient than doing needless iterations in the outer loop, is to do while(flag) where flag is set to false if there was no swap. Something like the one here:

http://mathbits.com/MathBits/Java/arrays/Bubble.htm

0

Maybe this is an academic experiment in writing bubble sorts, but if it's not, there's no need to write your own sorting algorithm. Arrays.sort can easily sort it, or any portion of it:

Arrays.sort(clipArray, 0, 2, new Comparator<Clip>() {
    public int compare(Clip c1, Clip c2) {
        return c1.getSurname().compareToIgnoreCase(c2.getSurname());
    }
});
0

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.