überprüfen, ob ich Sie richtig verstanden, Sie eine Klasse bekam, die als generische Typ dient und wollen wissen, wie man Verwenden Sie dazu die Vergleichsschnittstelle. Hier ist mein Versuch:
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));
}
}
Wenn Sie das Hauptverfahren ausführen, das erste Array-Element wird auf der Rückseite des Arrays, weil 1 < 2 und ‚a‘ < ‚e‘ (auch 3,5 < 1,5 gesetzt werden, aber wir gehen nicht dorthin, weil wir eine Reihenfolge haben, in der die Felder verglichen werden) Beantwortet das die Frage?
EDIT: Dies sollte es jetzt tun.
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()));
}
}
Was meinen Sie mit "Auftragsfeld des Objekts"? Kannst du uns ein Beispiel geben? – Pshemo