问题描述
我们有一些代码根据坐标之间的距离对地址列表进行排序。这是通过collections.sort和自定义比较器完成的。
We have some code wich sorts a list of addresses based on the distance between their coordinates. this is done through collections.sort with a custom comparator.
但是,有时会在列表中出现没有坐标的地址,从而导致出现NullPointerException。我最初的想法是让比较器返回0作为地址的距离,其中至少有一个坐标为空。我担心这可能会导致列表中'有效'元素的顺序损坏。
However from time to time an adress without coordinates is in the list causing a NullPointerException. My initial idea to fix this was to have the comparator return 0 as dististance 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.
所以在比较器ok中返回空数据的'0'值,或者有更清洁的方法来解决这个问题。
so is returning a '0' values for null data in a comparator ok, or is there a cleaner way to resolve this.
推荐答案
处理它像 null
意味着无限远。因此:
Handle it like null
means infinitely far away. Thus:
-
comp(1234,null)== -1
-
comp(null,null)== 0
-
comp(null ,1234)== 1
comp(1234, null) == -1
comp(null, null) == 0
comp(null, 1234) == 1
通过这种方式,您可获得一致的订购。
With this, you get a consistent ordering.
这篇关于具有空值的比较器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!