Comparing objects using equality and a comparable interface

Can someone explain to me if there is a difference in the codes below when comparing objects and, more specifically, their values.

Code 1

x.equals(y)

Code 2

x.compareTo(y) == 0

Are the codes above interchangeable. What is the difference, if any?

+4
source share
3 answers

From comparable

Highly recommended, but not strictly required, to (x.compareTo (y) == 0) == (x.equals (y)). Generally speaking, any class that implements the Comparable interface and violates this condition should clearly indicate this fact. Recommended language: "Note: this class has a natural ordering that is incompatible with peers."

How @ZouZ to mention

C , e1.compareTo(e2) == 0 e1.equals(e2) e1 e2 C. , null , e.compareTo(null) NullPointerException, e.equals(null) false.

, .

, java api, BigDecimal

import java.math.BigDecimal;

public class Test{
 public static void main(String args[])  {

       BigDecimal big = BigDecimal.ZERO;
       BigDecimal zero  = new BigDecimal("0.00");

       System.out.println("Compare "+ (big.compareTo(zero) == 0) ); //prints true
       System.out.println("Equals "+big.equals(zero)); // prints false      
 } 
}
+2

compareTo , .
> , equals , Object.

equals, compareTo, .

.

+1

It is not interchangeable for strings.

x.equals((String)null)  returns false

Code 2

x.compareTo((String)null) == 0 // throws a NullPointerException

See here: Java Strings: compareTo () vs. equals ()

0
source

All Articles