【发布时间】:2016-10-11 11:43:40
【问题描述】:
我有一个包含对象字段 4 的数组列表。我需要知道如何使用执行算法的通用方法(isort、msort、qsort)“一个接一个”地对对象的字段进行排序。
我知道比较器接口,但不知道如何检查泛型类型 T 中的所有字段。
【问题讨论】:
-
“对象的订单字段”是什么意思?你能给我们举个例子吗?
标签: java arraylist generic-programming
我有一个包含对象字段 4 的数组列表。我需要知道如何使用执行算法的通用方法(isort、msort、qsort)“一个接一个”地对对象的字段进行排序。
我知道比较器接口,但不知道如何检查泛型类型 T 中的所有字段。
【问题讨论】:
标签: java arraylist generic-programming
如果我的理解正确,您有一个用作泛型类型的类,并且想知道如何使用 Comparator 接口。这是我的尝试:
class ClassWithFields {
int fieldA;
double fieldB;
String fieldC;
public ClassWithFields(int fieldA, double fieldB, String fieldC) {
this.fieldA = fieldA;
this.fieldB = fieldB;
this.fieldC = fieldC;
}
@Override
public String toString() {
return "["+fieldA+","+fieldB+","+fieldC+"]";
}
}
public class GenericComparator<T extends ClassWithFields> implements Comparator<T> {
@Override
public int compare(T o1, T o2) {
if (o1.fieldA < o2.fieldA)
return -1;
else if (o1.fieldA > o2.fieldA)
return +1;
else if (o1.fieldB < o2.fieldB)
return -1;
else if (o1.fieldB > o2.fieldB)
return +1;
else
return o1.fieldC.compareTo(o2.fieldC);
}
public static void main(String[] args) {
ClassWithFields[] cwfArray = new ClassWithFields[3];
cwfArray[0] = new ClassWithFields(2, 1.5, "Test");
cwfArray[1] = new ClassWithFields(1, 3.5, "Test");
cwfArray[2] = new ClassWithFields(2, 1.5, "Tast");
Arrays.sort(cwfArray, new GenericComparator<ClassWithFields>());
System.out.println(Arrays.toString(cwfArray));
}
}
当你运行 main 方法时,第一个数组项将被放在数组的后面,因为 1
编辑:现在应该这样做了。
public class GenericComparator<T extends ClassWithFields> implements Comparator<T> {
private String fieldIdentifier;
public GenericComparator(String fieldIdentifier)
{
this.fieldIdentifier = fieldIdentifier;
}
@Override
public int compare(T o1, T o2) {
if (fieldIdentifier.equals("fieldA")) {
if (o1.fieldA < o2.fieldA)
return -1;
else if (o1.fieldA > o2.fieldA)
return +1;
return 0;
}
else if (fieldIdentifier.equals("fieldB")) {
if (o1.fieldB < o2.fieldB)
return -1;
else if (o1.fieldB > o2.fieldB)
return +1;
return 0;
}
else
return o1.fieldC.compareTo(o2.fieldC);
}
public static <S extends ClassWithFields> void isort(ArrayList<S> array, String type) {
Comparator<S> comp = new GenericComparator<S>(type);
// TODO employ search algorithm
S help = null;
for (int i = 0; i < array.size(); i++) {
for (int j = 0; j < array.size(); j++) {
if (comp.compare(array.get(i), array.get(j)) > 0) {
help = array.get(i);
array.set(i, array.get(j));
array.set(j, help);
}
}
}
}
public static void main(String[] args) {
ClassWithFields[] cwfArray = new ClassWithFields[3];
cwfArray[0] = new ClassWithFields(2, 1.5, "Test");
cwfArray[1] = new ClassWithFields(1, 3.5, "Test");
cwfArray[2] = new ClassWithFields(2, 1.5, "Tast");
ArrayList<ClassWithFields> cwfList = new ArrayList<ClassWithFields>();
Collections.addAll(cwfList, cwfArray);
isort(cwfList, "fieldA");
System.out.println(Arrays.toString(cwfList.toArray()));
}
}
【讨论】: