How to choose between Comparable and Comparator in Java

Comparable and Comparator Interfaces in Java

In this post, we’ll see why we need Comparable and Comparator Interfaces, how to use and when to use. We’ll also look into the difference between between in terms of their requirement and use.

As their name suggest, Comparable and Comparator Interfaces are used to compare similar objects for example, while performing searching and sorting.
Assume that you have a container containing a list of Person object.Now, how you compare two Person objects? There are any number ofcomparable attributes, such as SSN, name, driving-license number, and so on. Two objects can be compared on SSN as well as person’s name; this depends on the context. Hence, the criterion to compare the Person objects cannot be predefined; a developer has to define this criterion. Javadefines Comparable and Comparator interfaces to achieve the same.

Click here to read more

 

Advertisements

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