comparator with null values

前端 未结 9 1153
萌比男神i
萌比男神i 2020-12-04 16:25

We have some code which sorts a list of addresses based on the distance between their coordinates. this is done through collections.sort with a custom comparator.

How

相关标签:
9条回答
  • 2020-12-04 16:53

    I personally hate dealing with special null cases everywhere in my comparators so i was looking for a cleaner soluation and finally found google collections. Their Ordering is just awesome. They support compound comparators, offer to sort nulls to the top and to the end and allow to run certain functions before comparing. Writing comparators has never been so easy. You should give it a try.

    0 讨论(0)
  • 2020-12-04 17:04

    Handle it like null means infinitely far away. Thus:

    • comp(1234, null) == -1
    • comp(null, null) == 0
    • comp(null, 1234) == 1

    With this, you get a consistent ordering.

    0 讨论(0)
  • 2020-12-04 17:09

    Instead of looking at this like it's a technical problem with the comparator, it's better to take a look at the requirements again: what you're really trying to do here, what are you going to do with this sorted list?

    • If you are trying to sort them to show the most relevant solutions first to a user, it might be a good idea to put the unknown locations last, so treat it like infinity (returning 0/-1/1 depending on which of them is null).
    • If you are going to use this result to draw some graph or do some other calculations that depend on them really being sorted by their distance, then the nulls probably shouldn't have been in there anyways (so either remove them first, or throw an exception if at that point there actually weren't supposed to be any addresses with a null location).

    As you already realize, always returning 0 when one of them is null is not a good idea here; it can corrupt the result indeed. But what you should do instead depends on what you need, not on what others usually do/need. How your program behaves with addresses that don't have a location (so what the user is going to see) should not depend on some technical detail like what the "best practice" for comparators is. (To me, asking what the "best practice" is here, sounds like asking what the "best requirements" are).

    0 讨论(0)
提交回复
热议问题