This week's book giveaway is in the Big Data forum.
We're giving away four copies of Elasticsearch in Action and have Radu Gheorghe & Matthew Lee Hinman on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes I m still not understanding COMPARABLE Interface Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Elasticsearch in Action this week in the Big Data forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "I m still not understanding COMPARABLE Interface" Watch "I m still not understanding COMPARABLE Interface" New topic

I m still not understanding COMPARABLE Interface

saurabhthard aggarwal

Joined: Nov 20, 2008
Posts: 22
please give me SIMPLE ,COMPLETE example of Comparable interface.Also its main features.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14599

The reason why you're not getting good answers is because your question is very vague and general. Can you explain in more detail what exactly you don't understand about the Comparable interface?

Did you read the API documentation? What part of it did you not understand? Have a look at The Collections Framework, which explains how collections work, including the Comparable interface.

Try writing some code yourself to find out how it works. If your code doesn't work, post it here and ask questions about it.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Deepak Bala

Joined: Feb 24, 2006
Posts: 6662

Does this help

SCJP 6 articles - SCJP 5/6 mock exams - More SCJP Mocks
K. Tsang

Joined: Sep 13, 2007
Posts: 2726

a more common problem would be whether to use the java.lang.Comparable interface or the java.util.Comparator interface. The goal of both of these interface is what?? sort object right?

Comparable uses the "compareTo(Object o)" method
Comparator uses the "compare(Object o1, Object o2)" method

If you implement either of these interfaces you normally override the equals and hashCode methods and good idea to override toString too.

Both of the above methods uses the equals method to compare in order to sort that object.

Talking about sort, using Collection.sort() only sort strings and primitive collections. More complicated objects would not be appropriate so using either of these is the way to go.

At the end of the day, use Comparable to do simple sorting, otherwise use Comparator to have more control.

Best to is to test out both by sorting the same object.

I agree. Here's the link:
subject: I m still not understanding COMPARABLE Interface