java2db

Java comparable and comparator interfaces example



To sort a list of objects by natural or custom order based on the object fields(identity,name,date,…), use the comparable and comparator interfaces.

The main differences between java comparable and comparator interfaces are given below.

Comparable :
comparable and comparator interfaces Comparable interface is in java.lang package .
comparable and comparator interfaces we must implement the Comparable interface , override compareTo() method in the class that   …….whose objects are being sorted (The Student class in the below example).
comparable and comparator interfaces The method compareTo(Object o1)  returns ,
…… comparable and comparator interfaces positive (1)    : if the current value(this.value) is greater than o1.value.
…… java comparable and comparator zero (0)         : if the current value(this.value) equals to o1.value.
…… comparable and comparator interfaces negative (-1) : if the current value(this.value) is lesser than o1.value.
java comparable and comparator Comparable is used when the objects need to be compared in their natural order.

 

Comparator :
java comparable and comparator Comparator interface is in java.util package
java comparable and comparator We can implement the Comparator interface , override compare() method either instantiated class …….(The class comparatorExe ) or the class that whose objects are being sorted (The class  Student).
java comparable and comparator The method compare(Object o1, Object o2) returns
…… java comparable and comparator positive (1)   : if o1.value is greater than o2.value.
…… comparable and comparator interfaces zero     (0)     : if o1.value equals to o2.value.
…… java comparable and comparator negative (-1) : if o1.value is lesser than o2.value.
java comparable and comparator Comparator is used when the objects need to be compared in custom user-defined order.

 

java comparable and comparator Sorting with Comparable interface example :
comparable and comparator interfaces  Student class :

java comparable and comparator comparableExe class :

 

java comparable and comparator Sorting with Comparator interface example:
java comparable and comparator Student class :

java comparable and comparator comparatorExe class :

java comparable and comparator We can also implement The Comparator interface like Comparable interface in  the class that   …….whose objects are being sorted .

 




Related Posts :
   [will not be published]



^ <