top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Why equals() method must be compatible with compareTo in java ?

+3 votes
3,492 views
Why equals() method must be compatible with compareTo in java ?
posted Sep 8, 2013 by Vinay Shukla

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+1 vote

Please go through this following link. Hope this will help you.
http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html

answer Sep 16, 2013 by Satyabrata Mahapatra
–1 vote

CompareTo() method in Java must be compatible with equals method in Java i.e. if two objects are equal via equals method compareTo method must return “0″ for them, failing this may result in some subtle bug when you store those objects in collection class like arraylist in java. For detailed answer check here http://javarevisited.blogspot.in/2011/02/how-to-write-equals-method-in-java.html

answer Sep 9, 2013 by Arvind Singh
They are not same "abc".equals((String)null) returns false while "abc".compareTo((String)null) == 0 throws a NullPointerException. So they are not always interchangeable even for Strings.
Similar Questions
+1 vote

Give proper explanation.

I am new in Java but I have knowledge about C programming.

+2 votes

Why do I need to override the equals and hashCode methods in Java? I mean Why always override hashcode() if overriding equals()?

...