Generally I define Comparator as –
Comparator<Obj> comparator= new Comparator<Obj>() {
public int compare(Obj o1, Obj o2) {
//implementation...
}
};
And when the Comaprator is a part of class memeber’s it’s slightly does not looks good on the code format . Is there any way to define the Comparator as Comparator<Obj> comparator= new Comparator<Obj>() and implement his compare in another section ?
Just define a
classthat implementsComparatorinterface, and implement thecomparemethod in that class, with yourcomparison logic: –And then, where-ever you want to use your
Comparator, use an instance of this class. For example, inArrays.sort: –