Rudresh Rudresh - 1 month ago 21
Java Question

Create a dynamic sort comparator

I'm a C# developer trying to work on Java. I'm stuck in creating a dynamic comparator. below is the code

public class SortImpl implements Sort {
public SortImpl() {
}

public ArrayList<Comparable> sort(ArrayList<Comparable> var1) {
Comparator var2 = new Comparator() {
};
var1.sort(var2);
return var1;
}
}


But Comparator needs a type while creating a Comparator object. My ArrayList can be of any type like int, double, float. Please let me know what I am doing wrong.

Answer

You don't need to implement a Comparator at all if you use java.util.Collections for sorting the list: it will then be sorted according to the natural ordering of its elements:

public ArrayList<Comparable> sort(ArrayList<Comparable> var1) {
    Collections.sort(var1);
    return var1;
}