I know that an interface cannot have constructors and we cannot make object of interface.
This is not possible:
Comparator cmp = new Comparator();
I don't understand how is it possible to make an anonymous inner class with the keyword "new Comparator()". Doesn't this keyword create an object of the type Comparator?
Here is the complete code:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class DemoApp {
public static void main(String args[]) {
List<String> animals = new ArrayList<>();
animals.add("elephant");
animals.add("snake");
animals.add("lion");
animals.add("mangoose");
animals.add("cat");
animals.add("tiger");
Collections.sort(animals, new Comparator<String>() {
public int compare(String s1, String s2) {
return -s1.compareTo(s2);
}
});
displayList(animals);
}
public static void displayList(List<String> anim) {
for (String animal : anim) {
System.out.print(animal + " ");
}
System.out.println();
}
}
Java Comparator is an interface for sorting Java objects. Invoked by “java. util. comparator,” Java Comparator compares two Java objects in a “compare(Object 01, Object 02)” format. Using configurable methods, Java Comparator can compare objects to return an integer based on a positive, equal or negative comparison.
This interface is present in java. util package and contains 2 methods compare(Object obj1, Object obj2) and equals(Object element). Using a comparator, we can sort the elements based on data members. For instance, it may be on roll no, name, age, or anything else.
sort() methods automatically uses the compareTo() method of the class. For Comparator, client needs to provide the Comparator class to use in compare() method.
The many if-else-statements make the comparator somewhat clumsy and unreadable. Keep in mind that the compare method is not bound to returning -1, 0, or 1. It can return any negative number if the first argument is less than the second one, and any positive number if the first argument is greater than the second one.
Doesn't this keyword create an object of the type Comparator?
Yes it does, but it doesn't create an instance of class Comparator
(since Comparator
is not a class).
It create an instance of an anonymous class that implements the Comparator
interface. Since that class instance implements Comparator
, you can say that its type is Comparator
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With