Java – comparator not found

comparatorjava

I have to order a collection and I use a comparator

import java.util.*;

public class OpereComparatorAuthor implements Comparator<Opera>{

    public int compare(Opera left,Opera right){     
        return left.getArtist().compareTo(right.getArtist());
    }
} 

but when i call it from another class:

Collections.sort(ordbyauthor,OpereComparatorAuthor);

I receive this error:

cannot find symbol
symbol  : variable OpereComparatorAuthor
location: class Museo
    Collections.sort(ordbyauthor,OpereComparatorAuthor);

why?

Best Answer

You have to pass an object of the comparator:

Collections.sort(ordbyauthor, new OpereComparatorAuthor());

Update:

This is just a suggestion. Instead of defining a class, use anonymous class (which I think is a good candidate) for this kind of situation.

e.g.

//I am using Sala here instead of Opera as per your comment
Collections.sort(ordbyauthor, new Comparator<Sala>(){
    @Override
    public int compare(Sala left, Sala right) {
        //do your comparision here according to your requirement
        //then return the result
    }
});
Related Topic