top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration

Facebook Login
Site Registration

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

+3 votes
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.

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

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()?

Contact Us
+91 9880187415
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Karnataka INDIA.