Using a reference variable to point to a comparator?

During the exercise, I came across a new way of creating Comparator. Can someone explain this a bit?

class Checker{    
    public Comparator<Player> desc = new Comparator<Player>() {
        public int compare(Player A, Player B){
            if(A.score < B.score){
                return 1;
            }
            else if(A.score == B.score){
                return B.name.compareTo(A.name);
            }
            else{
                return -1;
            }
        }
    };
}

In the past, I have seen people do this:

class Checker implements Comparator{
    @Override
    public int compare(Player A, Player B){
        ..........
        ..........
    }
}

So, the first example really seems new to me (because I'm new?). This makes sense: desc can be a property / instance variable of a class Checkerthat points to a new instance of the Comparatorclass / interface class. However, are there any more stories behind these two different ways :? All of them require the creation of another class, so I do not see how you can be more organized.

+4
source share
1
+3

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


All Articles