// this function can be called if the objects sent is Comparable (they have
// already chosen the field and how it compares)
public void mySort(Object [] obj) {
Arrays.sort(obj, null); // this sorts based on compareTo()
// method of comparable object
}
My question is how would the following function need to be changed to sort the array by the Field field. I have tried many different ways of implementing it and just put code below which represents what I was trying to do.
// this function should be used to sort a generic array of T objects, to be
// compared on the Field field
public static <T> void mySort2(T [] obj, Field field) {
Collections.sort(obj, new Comparator<T>(){
public int compare(T obj1, T obj2)
{
return obj1.field.compareTo(obj2.field); // this does not work
// since I need to the name of the field and
// not a variable, however I do not know what
// T will be when it is sent to me
}
});
}
You need to use Field::get
to reflectively access the field. After that, you will need to cast to Comparable
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With