Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

However from time to time an address without coordinates is in the list causing a NullPointerException. My initial idea to fix this was to have the comparator return 0 as distance for addresses where at least one of the coordinates is null. I fear this might lead to corruption of the order the 'valid' elements in the list.

so is returning a '0' values for null data in a comparator ok, or is there a cleaner way to resolve this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
210 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...