简体   繁体   English

设计比较器的最佳方法是访问可能为空或为null的字符串字段

[英]Best way to design a Comparator accessing String fields that might be empty or null

I have to sort a Collection by different String attributes that might be empty ( "" ) or even null . 我必须按可能为空( "" )甚至为null的不同String属性对Collection进行排序。 Both values are allowed and have to be treated equally. 这两个值都是允许的,必须同等对待。

I solved this issue by using a method, that checks each String for null and returns an empty String, when null is found. 我通过使用一种方法解决了这个问题,该方法检查每个String是否为null并在找到null时返回一个空String。


So far my Comparator looks basicly like this 到目前为止,我的比较器基本上看起来像这样

public class MyComparator implements Comparator<MyObject> {

    @Override
    public int compare(MyObject o1, MyObject o2) {
        // ... some logical stuff like e.g.
        return rein(o1.getSomeValue()).compareTo(rein(o2.getSomeValue());
    }

    private String rein(String str) {
        return str == null ? "" : str;          
    }
}

I wonder if this design is considered to be ok or if there are reason against it? 我想知道这种设计是否还可以,还是有理由反对? If it is not ok, what else may I do to fulfil my requirements? 如果还不行,我还可以做什么来满足我的要求? All those (in most cases unneccessary) function calls looks ugly to me, as we are talking about approximately 1/1000 cases. 所有这些(大多数情况下都是不必要的)函数调用对我来说看起来很丑,因为我们谈论的是大约1/1000情况。 So I wonder if there is a more elegant solution? 所以我想知道是否有更优雅的解决方案?

Nothing wrong here. 没错 If you omit 'rein' method you will get NullPointerException in case when o1.getSomeValue() returns null. 如果省略“ rein”方法,则当o1.getSomeValue()返回null时,将获得NullPointerException。 So this check is necessary for correct compare method working. 因此,此检查对于正确的比较方法工作是必需的。 It's hard to imagine more elegant solution. 很难想象会有更优雅的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM