Recently I'm trying to get more familiar with the Comparator interface in Java. I have an exercise which is about to sort the ArrayList of strings from the shortest to longest. I used a Comparator of Strings. When searching the net, I found the following solution proposal:
public static Comparator<String> lengthComparator = new Comparator<String>() {
@Override
public int compare(String a, String b) {
if (a.length() == b.length()) {
return a.compareTo(b);
} else {
return (a.length() > b.length() ? 1 : -1);
}
}
};
Then I used it in my code to sort the set:
Collections.sort(set, lengthComparator);
And it worked. What I'd like to ask is the specific way of defining the lengthComparator object here. We create a new object:
new Comparator<String>()
with the default constructor. But then there is a further code with overwritten method in "{}" brackets. Is it a normal way of creating objects? I've never met it before and I'd like to learn more about it. Could you please advise me some referal materials where I can find more informations about it?