java - Comparison method violates its general contract -
i'm trying sort list. used collections.sort(list)
, , got illegalargumentexception exception.
know works on jdk6 , jdk7 using timsort. rules got below. think got right, doesn't work.
is there can give me situation code doesn't work? lot
rules:
> 1.sgn(compare(x, y)) == -sgn(compare(y, x)) > > 2.((compare(x, y)>0) && (compare(y, z)>0)) implies compare(x, z)>0 > > 3.compare(x, y)==0 implies sgn(compare(x, z))==sgn(compare(y, z)) z //stringutil.isblank(str) return if str==null||str.trim().length()==0 @override public int compareto(novelchapter o) { if(o == null){ return 1; } else if(o.equals(this) || == o){ return 0; } if(!stringutil.isblank(o.getsourceurl())&& !stringutil.isblank(this.getsourceurl())){ if(o.getsourceurl().length() != this.getsourceurl().length()){ return o.getsourceurl().compareto(this.getsourceurl()); } else{ return o.getsourceurl().compareto(this.getsourceurl()) * (-1); } } else if(!stringutil.isblank(o.getsourceurl())&& !stringutil.isblank(this.getsourceurl())){ return 1; } else if(!stringutil.isblank(o.getsourceurl())&& stringutil.isblank(this.getsourceurl())){ return -1; } else{ return 0; } }
btw, system.setproperty("java.util.arrays.uselegacymergesort", "true");
using jdk6, not solve problem itself.
================================================
thanks answers,and changed code,now throw npe .is better ?but still give me same exception.
@override public int compareto(novelchapter o) { if(o == null){ throw new nullpointerexception(); }else if(o.equals(this) || == o){ return 0; } string self = this.getsourceurl(); string item = o.getsourceurl(); if(self == null && item != null){ return -1; }else if (self == null && item != null){ return 1; }else if(self == null && item == null){ return 0; } if(self.length() == item.length()){ return self.compareto(item); }else{ return self.compareto(item) * (-1); } }
i can't see specific cause of exception, there couple of problems in code have shown us.
the
compareto
method should not used onnull
, special handling ofnull
should not there. comparator >>should<< throw npe. (and corollary should not attempting sort arrays / collections containnull
values.)your use of
trim
looks inconsistent. trim when "blank" urls, not when comparing "non-blank" urls. weird.
i add code verbose , inefficient. rather repeatedly calling isblank
utility in chain of if / else statements should convert 2 urls strings (i'm guessing) can compared directly.
finally, fact have have isblank
method @ says (to me) rest of code doing poor job of maintaining data consistency. there should 1 representation means "no source url" ... not (at least) three.
there number of possible causes of problem can eliminated examining complete classes involved ... starting novelchapter
, whatever getsourceurl()
returns.
Comments
Post a Comment