ObservableList javafx 使用比较器降序排序

ObservableList javafx sort descending with Comparator

ObservableArrayList.sorted 适用于原始数据类型,但如果引用数据类型则无法使用

ObservableList<NewClass> observableArrayList = FXCollections.observableArrayList();
            observableArrayList.add(new NewClass(1, "name 1"));
            observableArrayList.add(new NewClass(2, "name 2"));
            observableArrayList.add(new NewClass(4, "name 4"));
            observableArrayList.add(new NewClass(5, "name 5"));
            observableArrayList.add(new NewClass(3, "name 3"));

            observableArrayList.sorted(Comparator.reverseOrder());


class NewClass
private int stt
private int name

错误信息

incompatible types: inference variable T has incompatible bounds
    equality constraints: sf.enforcement.NewClass
    upper bounds: java.lang.Comparable<? super T>

我想按照Newclass的stt顺序排序,请帮帮我

Comparator.reverseOrder 仅在有反向命令时才有效。只有 NewClass 实现 Comparable 时才会出现这种情况。否则你需要使用自定义比较器:

observableArrayList.sort((a, b) -> Integer.compare(b.getStt(), a.getStt()));

Comparator<NewClass> comparator = Comparator.comparingInt(NewClass::getStt);
observableArrayList.sort(comparator.reversed());