“Comparison method violates its general contract!”

前端 未结 11 2041
梦如初夏
梦如初夏 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:40

    The violation of the contract often means that the comparator is not providing the correct or consistent value when comparing objects. For example, you might want to perform a string compare and force empty strings to sort to the end with:

    if ( one.length() == 0 ) {
        return 1;                   // empty string sorts last
    }
    if ( two.length() == 0 ) {
        return -1;                  // empty string sorts last                  
    }
    return one.compareToIgnoreCase( two );
    

    But this overlooks the case where BOTH one and two are empty - and in that case, the wrong value is returned (1 instead of 0 to show a match), and the comparator reports that as a violation. It should have been written as:

    if ( one.length() == 0 ) {
        if ( two.length() == 0 ) {
            return 0;               // BOth empty - so indicate
        }
        return 1;                   // empty string sorts last
    }
    if ( two.length() == 0 ) {
        return -1;                  // empty string sorts last                  
    }
    return one.compareToIgnoreCase( two );
    

提交回复
热议问题