-2

I have this function:

final ArrayList<Addressable> tempStoreList = new ArrayList<>();
tempStoreList.addAll(addressables);

    Collections.sort(tempStoreList, new Comparator<Addressable>() {
        @Override
        public int compare(Addressable o1, Addressable o2) {

            double distanceToO1 = 0;
            double distanceToO2 = 0;

            if (o1.getAddress() == null) {
                return (o2.getAddress() == null) ? 0 : -1;
            }
            if (o2.getAddress() == null) {
                return 0;
            }

            if (userLocation != null && o1.getAddress() != null && o2.getAddress() != null) {
                distanceToO1 = GlobalUtilities.distance(userLocation, o1.getAddress().getLocation(), "K");
                distanceToO2 = GlobalUtilities.distance(userLocation, o2.getAddress().getLocation(), "K");
            }

            if (distanceToO1 < distanceToO2) {
                return -1;
            } else if (distanceToO1 > distanceToO2) {
                return 1;
            } else {
                return 0;
            }

        }
    });

For some reason, I keep getting a NPE on:

if (o2.getAddress() == null) {
    return 0;
}

Which to me means that null was somehow placed in the array. Anyone ever encounter this before?

Mikerizzo
  • 587
  • 1
  • 4
  • 22
  • `addressables` already contains the `null`. Check there. – Henry Oct 19 '17 at 13:17
  • Null is a valid list value – Mike Oct 19 '17 at 13:18
  • 1
    Find out why your sequence contains a null element and fix _that_ issue. For cases where it's _not_ exceptional for a sequence to contain null elements, you can wrap your `Comparator` with `Comparator.nullsFirst` or `Comparator.nullsLast` (assuming Java 8 or later). Note that `Comparator` implementations are not required to support null values, so if that is something you want to handle, you should use one of the aforementioned wrappers. – Mike Strobel Oct 19 '17 at 13:18

2 Answers2

1

That means you need to check o2 reference. It may be null. Before getting adress from o2.getAddress first check o2 == null

Abdul Waheed
  • 4,540
  • 6
  • 35
  • 58
1

Yes, you can have null elements in your array list.

Try this:

final ArrayList<Object> list = new ArrayList<Object>();
list.add(null);

So, if you cannot guarantee that you will always have valid objects, change your code to

if (o2 == null || o2.getAddress() == null) {
    return 0;
}
Luis
  • 709
  • 8
  • 10