Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using reference variable to point to a Comparator?

I ran into a new way of creating Comparator while doing exercises. Can anyone explain this a little 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 only seen people doing this:

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

So the first example really seems novel to me(because I am a beginner?). It does make sense: desc could be an property/instance variable of class Checker which points to a new instance of Comparator class/interface. However are there more stories behind these two different ways of doing things? They all require creating a different class so I don't see how either one could be more organized.

like image 538
whales Avatar asked Oct 18 '22 18:10

whales


1 Answers

Both the syntax are absolutely correct. In first case you are simply using concept of anonymous class. In second you created a class Checker which implements compare method.

As a beginner it is much easier to understand second syntax other than that there is no difference between the two.

You can study more about anonymous class here -

https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html

If you want to use comparator at more places its better to use solution in separate class than anonymous one. Anonymous vs class solution is something like inline css style vs style classes.

like image 150
Mandeep Rajpal Avatar answered Oct 29 '22 15:10

Mandeep Rajpal