0

Trying to bubble sort an array of 2 objects, the comments are what the 2 positions (0 and 1) contain. It does actually populate the array. When I'm comparing ownerArray[j] and ownerArray [j+1] I get a null pointer exception, because I'm referring to a null value because the array isn't that large. Any clue how to fix this while still being able to refer to the next position of the array?

 public void sortOwners() {
    try {
        model = (DefaultTableModel) SortedOwners.jTable1.getModel();
        model.setRowCount(0);

        populateOwners();

        size2 = ownerArray.length;

        // ownerArray[0]  = 9900000000000 Reenen Muller xxxxxx@xxxxx.co.za
        //  ownerArray[1] = 8800000000000 John   Doe    yyyyyy@yyyyy.co.za
        for (int i = 0; i < size2; i++) {
            for (int j = 1; j < size2 - i; j++) {

                if ((ownerArray[j].getFirstName()).compareTo(ownerArray[j + 1].getFirstName()) < 0) {

                    Owner temp3 = ownerArray[j];
                    ownerArray[j] = ownerArray[j + 1];
                    ownerArray[j + 1] = temp3;


                }

            }
        }

        viewAllOwners();

    } catch (Exception e) {
        e.printStackTrace();

    }
Michael
  • 41,989
  • 11
  • 82
  • 128
  • 1
    You may want to edit out those email-adresses. – Seth Apr 03 '17 at 10:06
  • 2
    You should compare (and swap) `j`-th element with `i`-th element, not `j+1`-th... – radoh Apr 03 '17 at 10:07
  • Also, I hope this is only an exercise, and you're not planning on using Bubble sort in some production code :) – radoh Apr 03 '17 at 10:08
  • 1
    Sure you get a `NullPointerException`? I think it should be an `IndexOutOfBoundsException` in your first iteration of `i` and the last iteration of `j`. In that case `j+1` is equal to `ownerArray.length` – Stefan Warminski Apr 03 '17 at 10:10
  • You need to fix your nested `for` loops. You find a way to iteraate 2D array [here](http://stackoverflow.com/questions/2893297/iterate-multi-dimensional-array-with-nested-foreach-statement) – MUT Apr 03 '17 at 10:11
  • 1
    @radoh It's a long time ago but in bubble sort I need to compare two neighbors, don't I? – Stefan Warminski Apr 03 '17 at 10:11
  • I have reproduced the `ArrayIndexOutOfBoundsException` @StefanWarminski talked about. – Ole V.V. Apr 03 '17 at 10:52
  • 1
    @StefanWarminski ah, you're right. Then OP should compare with previous element, since he is iterating `j` from `1`, that is, compare `j` with `j-1`. – radoh Apr 03 '17 at 11:14
  • 1
    Ah thanks so much @radoh! , haven't slept in a while so I made a simple error. – rmull17 Apr 03 '17 at 15:10

0 Answers0