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 [email protected]
        //  ownerArray[1] = 8800000000000 John   Doe    [email protected]
        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();

    }
9
  • 1
    You may want to edit out those email-adresses. Commented Apr 3, 2017 at 10:06
  • 2
    You should compare (and swap) j-th element with i-th element, not j+1-th... Commented Apr 3, 2017 at 10:07
  • 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 Commented Apr 3, 2017 at 10:10
  • 1
    @radoh It's a long time ago but in bubble sort I need to compare two neighbors, don't I? Commented Apr 3, 2017 at 10:11
  • 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. Commented Apr 3, 2017 at 11:14

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.