interface in Java is defined in java.lang package.
Comparator interface in Java has method public int compare
(Object o1, Object o2) which returns a negative integer, zero, or
a positive integer as the first argument is less than, equal to, or
greater than the second. While Comparable interface has method
public int compareTo(Object o) which returns a negative
integer, zero, or a positive integer as this object is less than, equal
to, or greater than the specified object.
If you see then logical difference between these two is
Comparator in Java compare two objects provided to him, while
Comparable interface compares "this" reference with the object
specified.
Comparable in Java is used to implement natural ordering of
object. In Java API String, Date and wrapper classes implement
Comparable interface.
If any class implement Comparable interface in Java then
collection of that object either List or Array can be sorted
automatically by using Collections.sort() or Arrays.sort() method
and object will be sorted based on there natural order defined by
CompareTo method
Example of Comparable
public class Person implements Comparable {
private int person_id;
private String name;
/**
* Compare current person with specified person
* return zero if person_id for both person is same
* return negative if current person_id is less than specified one
* return positive if specified person_id is greater than specified one
*/
public int compareTo(Person o) {
return this.person_id - o.person_id ;
}
….
}
Example of Comparator
package com.hardik4u.practice;And
import java.util.Comparator;
public class MyIntComparable implements Comparator<Integer>{
@Override
public int compare(Integer o1, Integer o2) {
return (o1>o2 ? -1 : (o1==o2 ? 0 : 1));
}
}
package com.hardik4u.practice;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Simple2 {
public static void main(String[] args)
{
List<Integer> list = new
ArrayList<Integer>();
list.add(5);
list.add(4);
list.add(3);
list.add(7);
list.add(2);
list.add(1);
Collections.sort(list, new
MyIntComparable());
for (Integer integer : list) {
System.out.println(integer);
}
}
No comments:
Post a Comment