How Do You Define a Comparator in Java
4. Comparator. the Comparator Interface Defines a Compare(Arg1, Arg2) Method with Two Arguments That Represent Compared Objects, and Works Similarly to the...
4. Comparator. The Comparator interface defines a compare(arg1, arg2) method with two arguments that represent compared objects, and works similarly to the Comparable. compareTo() method.
How do you create a comparator in Java?
- import java.util.*;
- class AgeComparator implements Comparator{
- public int compare(Object o1,Object o2){
- Student s1=(Student)o1;
- Student s2=(Student)o2;
- if(s1.age==s2.age)
- return 0;
- else if(s1.age>s2.age)
Must Read
What is an example of a comparator?
A comparator circuit compares two voltages and outputs either a 1 (the voltage at the plus side; VDD in the illustration) or a 0 (the voltage at the negative side) to indicate which is larger. Comparators are often used, for example, to check whether an input has reached some predetermined value.