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

前端 未结 17 2118
醉酒成梦
醉酒成梦 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条回答
  •  旧时难觅i
    2020-11-28 18:33

    You can extract method:

    public int cmp(String txt, String otherTxt)
    {
        if ( txt == null )
            return otjerTxt == null ? 0 : 1;
    
        if ( otherTxt == null )
              return 1;
    
        return txt.compareToIgnoreCase(otherTxt);
    }
    
    public int compareTo(Metadata other) {
       int result = cmp( name, other.name); 
       if ( result != 0 )  return result;
       return cmp( value, other.value); 
    

    }

提交回复
热议问题