Definition Of Comparator Interface

Definition Of Comparator Interface

Definition Of Comparator Interface ~ First of all, before reading this post you should understand what is an interface in craftingez6-coding.

You can found comparator interface in java.util.package and it contains 2 methods. Thus 2 of those methods are : .compare(obj1, obj2) and equals(Object element)

compare() method

public int compare(object1, object2)

Java Comparator Example (non-generic style)

Thus for this example I’ve created 2 class of sorting elements in the base of age and name. Due to the sake of simplicity of this article i’ve only created 2 :

  1. Age Comparator
  2. Name Comparator

Age Comparator :

Most of all this class defines a comparison between 2 object. If the first object is greater than the second object then it will output positive value (1, 2, 15 etc.). And if the first object is less than the second object then it will output negative value. If the first and the second object is equals it will returns  0.

import java.util.*;
class AgeComparatorExmpl implements Comparator{
public int compare(Object o1,Object o2){
Member  m1=(Member)o1;
Member m2=(Member)o2;

if(m1.age==m2.age)
return 0;
else if(m1.age>m2.age)
return 1;
else
return -1;
}
}

Name Comparator :

First of all This class defines a comparison based on logic such as name. due to this method we are using the compareTo() method from string class which provide us the comparison logic.

import java.util.*;
class NameComparator implements Comparator{
public int compare(Object o1,Object o2){
Member m1=(Member)o1;
Member m2=(Member)o2;

return m1.name.compareTo(m2.name);
}
}

Thus this is only an example, you don’t have to create all of comparator interface the same as mine. You probably can create something more noteworthy or you can tweak the way it works.

And that is the definition of comparator interface and it’s example. well it seems like this subject is the only thing I can give you this time. Of course it still need a lot of correction and because of that you can leave your commentar in the box below.

 

Leave a Reply

Your email address will not be published. Required fields are marked *