How to simplify a null-safe compareTo() implementation?

前端 未结 17 2018
醉酒成梦
醉酒成梦 2020-11-28 18:03

I\'m implementing compareTo() method for a simple class such as this (to be able to use Collections.sort() and other goodies offered by the Java pl

17条回答
  •  有刺的猬
    2020-11-28 18:34

    For the specific case where you know the data will not have nulls (always a good idea for strings) and the data is really large, you are still doing three comparisons before actually comparing the values, if you know for sure this is your case, you can optimize a tad bit. YMMV as readable code trumps minor optimization:

            if(o1.name != null && o2.name != null){
                return o1.name.compareToIgnoreCase(o2.name);
            }
            // at least one is null
            return (o1.name == o2.name) ? 0 : (o1.name != null ? 1 : -1);
    

提交回复
热议问题