JavaAntiPatterns

Collection of bad coding practices

‘compareTo()’ is incompatible with ‘equals()’

with one comment

If a class implements Comparable, compareTo() method must return zero if and only if equals() returns true for the same non-null argument (and vice versa). Violating this rule may cause unexpected behavior of the objects.

class Product implements Comparable
    ...
    public int compareTo(Object o) {
        if (o == null)
            throw new NullPointerException();
        if (this.equals(o))
            return 0;
        ...    
    }
}

See also:

Advertisements

Written by Alex

November 22, 2007 at 1:53 pm

Posted in Objects

Tagged with , ,

One Response

Subscribe to comments with RSS.

  1. The best bongs money can buy!…

    […]‘compareTo()’ is incompatible with ‘equals()’ « Java AntiPatterns[…]…

    The best bongs money can buy!

    February 16, 2012 at 2:29 am


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: