且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

当参数字符串为null时,int compareTo()应该返回什么?

更新时间:2023-11-30 23:11:58

是的,对于实例字段允许 null 没有问题 - 只需确保定义其排序顺序。最自然的是将它放在所有真正的琴弦之前或之后,但你可以在这里做任何事情,只要一贯地做。 (例如,您可以将 null 排序为null。)

Yes, there is no problem allowing null for instance fields - just make sure its sorting order is defined. Most natural would be putting it either before or after all real strings, but you could do anything here, just do it consistently. (For example, you could sort null like "null".)

以下是单个成员的示例实现:

Here is an example implementation for a single member:

class Example implements Comparable<Example> {

   @Nullable
   private String member;

   // TODO: getter, setter, constructor, ...

   public int compareTo(Example that) {
      if(this.member == null)
         if(that.member == null)
            return 0; //equal
         else
            return -1; // null is before other strings
       else // this.member != null
         if(that.member == null)
            return 1;  // all other strings are after null
         else
            return this.member.compareTo(that.member);
   }
}

请注意Comparable.compareTo()的规格只有 o.compareTo(null)的约束(它的行为应该像 - null.compareTo(o) ),但不是关于如何处理 null 字段(它根本没有提到字段,所以只要反对称性,反身性和反对性,类就可以返回它想要的任何东西。确保传递性。)

Please note that the specification of Comparable.compareTo() only has a constraint for o.compareTo(null) (which should behave just like - null.compareTo(o)), but not about how null fields are handled (it doesn't mention fields at all, so a class could return whatever it wants, as long as the antisymmetry, reflexivity and transitivity is ensured).