top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

Facebook Login
Site Registration
Print Preview

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

+3 votes
2,919 views
posted Sep 8, 2013 by Vinay Shukla

Share this question
Facebook Share Button Twitter Share Button Google+ Share Button LinkedIn Share Button Multiple Social 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()?


Useful Links with Similar Problem
Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#470/147, 3rd Floor, 5th Main,
HSR Layout Sector 7,
Bangalore - 560102,
Karnataka INDIA.
QUERY HOME
...