【发布时间】:2025-12-12 20:45:01
【问题描述】:
// 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
}
我的问题是如何更改以下函数以按字段字段对数组进行排序。我尝试了许多不同的实现方式,只是在下面放了代表我正在尝试做的代码。
// 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
}
});
}
【问题讨论】:
标签: java sorting generics field