Tuesday 15 May 2018

Comparable and Comparator in JAVA


             

Comparable and Comparator are two interfaces provided by Java Core API. From their names, we can tell they may be used for comparing stuff in some way. But what exactly are they and what is the difference between them? The following are two examples for answering this question. The simple examples compare two HDTV's size. How to use Comparable vs. Comparator is obvious after reading the code.

1. Comparable
Comparable is implemented by a class in order to be able to comparing object of itself with some other objects. The class itself must implement the interface in order to be able to compare its instance(s). The method required for implementation is compareTo().

2. Comparator

In some situations, you may not want to change a class and make it comparable. In such cases, Comparatorcan be used if you want to compare objects based on certain attributes/fields. For example, 2 persons can be compared based on `height` or `age` etc. (this can not be done using comparable.)

The method required to implement is compare(). Now let's use another way to compare those TV by size. One common use of Comparator is sorting. Both Collections and Arrays classes provide a sort method which use a Comparator.

No comments:

Post a Comment

😍Developer on Weekends #shorts #officememes #developermemes

😍Developer on Weekends #shorts #officememes #developermemes Welcome to the latest viral YouTube shorts meme for developers! 😍Developer on...