Need an easy way to create a comparator class used for sorting

I looked at the following Java tutorial , which shows how to sort by age for a Person object. To do this, you must create a class as follows:

class PersonAgeComparator implements Comparator<Person> {
public int compare(Person a, Person b) {
    return a.getBirthday().compareTo(b.getBirthday());
}
}

My question is, is there a simple way, such as a wizard, that can generate this code for me? I know that there is a wizard that can generate hashcode and equals, but what about the Comparator class, which is used for sorting. It really can be useful ... what if we had to sort by age and name? I would have no idea how to create this comparison method myself. A wizard can really help here.

+4
source share
1 answer

No, there is no such master. How could a computer know which variables to compare, and most importantly, how their relationships would work?

Another example of name comparison. Different designations have different comparisons when it comes to the alphabet, so the order of names may vary depending on location! All of them are very specific to the problem you are solving, and there are no general solutions.

0
source

Source: https://habr.com/ru/post/1526402/


All Articles