“Comparison method violates its general contract!”

前端 未结 11 2044
梦如初夏
梦如初夏 2020-11-21 06:07

Can someone explain me in simple terms, why does this code throw an exception, \"Comparison method violates its general contract!\", and how do I fix it?

pri         


        
11条回答
  •  感情败类
    2020-11-21 06:59

    Even if your compareTo is holds transitivity in theory, sometimes subtle bugs mess things up... such as floating point arithmetic error. It happened to me. this was my code:

    public int compareTo(tfidfContainer compareTfidf) {
        //descending order
        if (this.tfidf > compareTfidf.tfidf)
            return -1;
        else if (this.tfidf < compareTfidf.tfidf)
            return 1;
        else
            return 0;
    
    }   
    

    The transitive property clearly holds, but for some reason I was getting the IllegalArgumentException. And it turns out that due to tiny errors in floating point arithmetic, the round-off errors where causing the transitive property to break where they shouldn't! So I rewrote the code to consider really tiny differences 0, and it worked:

    public int compareTo(tfidfContainer compareTfidf) {
        //descending order
        if ((this.tfidf - compareTfidf.tfidf) < .000000001)
            return 0;
        if (this.tfidf > compareTfidf.tfidf)
            return -1;
        else if (this.tfidf < compareTfidf.tfidf)
            return 1;
        return 0;
    }   
    

提交回复
热议问题