witam, mam pytanie przechowuje obiekty w strukturze vector, jednym z pol obiektu jest pole typu data, chciałbym posortować obiekty w strukturze wg tego pola malejąco, proszę o podpowiedz jak to wykonac?
0
0
Zrób aby klasa która zawiera pole data implementowała interfejs Comparable(Zaimplementuj metode compareTo), a potem do sortowania użyj Collections.sort() ;-)
@Edit: ponieważ chcesz posortować w porządku malejącym to użyj wersji metody Collections.sort(List, Comparator)
Przykład:
package pl.kaziuuu;
public class Data {
private int data;
public Data(int data) {
this.data = data;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
}
package pl.kaziuuu;
import java.util.Collections;
import java.util.Comparator;
import java.util.Random;
import java.util.Vector;
public class Application {
public static void main(String[] args) {
Vector<Data> list = new Vector<Data>();
Random ran = new Random();
for (int i = 0; i < 100; i++) {
list.add(new Data(ran.nextInt()));
}
Collections.sort(list, new Comparator<Data>() {
public int compare(Data d1, Data d2) {
if (d1.getData() == d2.getData()) {
return 0;
} else if (d1.getData() < d2.getData()) {
return 1;
} else {
return -1;
}
}
});
for (Data ele : list) {
System.out.println(ele.getData());
}
}
}