[英]Setting type of ObservableList when using a custom class and Comparator
我正在尝试对在VBox内扩展HBox的自定义类的列表进行排序。 一切工作都很好,没有类型声明,但是我想知道是否有一种方法可以消除警告。
public static class FilePane extends HBox {}
public void sort() {
int order = orderBy.getSelectionModel().getSelectedIndex();
Comparator<FilePane> comp = null;
if(order == 0) {
comp = Comparator.comparing(FilePane::getFileNameLower);
} else if(order == 1) {
comp = Comparator.comparingLong(FilePane::getFileDate);
comp = comp.reversed();
} else if(order == 2) {
comp = Comparator.comparingLong(FilePane::getFileSize);
comp = comp.reversed();
} else if(order == 3) {
comp = Comparator.comparingLong(FilePane::getFileCount);
comp = comp.reversed();
} else if(order == 4) {
comp = Comparator.comparing(FilePane::getDirectory);
comp = comp.reversed();
}
ObservableList list = fileList.getChildren();
FXCollections.sort(list, comp);
}
尝试将list
设置为ObservableList<FilePane>
会出现错误,告诉我应将其设置为<Node>
因为那是getChildren()
返回的内容。 将其设置为<Node>
无效,并且FXCollections.sort(list, comp);
给出一个错误,指出FilePane将不起作用,因为:
The method sort(ObservableList<T>, Comparator<? super T>) in the type FXCollections is not applicable for the arguments (ObservableList<Node>, Comparator<FilePane>)
FilePane扩展了应该被认为是Node的HBox? 比较器的类型不能设置为Node,因为它需要具有要比较的类。 使用ObservableList<FilePane> list = (ObservableList<FilePane>) fileList.getChildren();
告诉我它不能做到这一点,所以这不是一个选择。
我应该忽略类型警告,因为没有它们就可以正常工作吗? 有没有一种方法可以将VBox的子级设置为ObservableList<FilePane>
?
如果getChildren()
返回Node
的列表,那么您需要将该列表作为Node
的列表。 让我们从那里开始并向后工作。
ObservableList<Node> list = fileList.getChildren();
好的。 如果那是列表,那么我们如何获得sort()
调用进行编译? 答案是比较器必须是Comparator<Node>
而不是Comparator<FilePane>
。
但这不好,对吗? 因为那样我们就不能使用那些真正漂亮的FilePane::
方法引用。 等一下,伙伴。 没那么快。 难道没有什么办法可以让该代码保持不变,并使sort()
感到高兴吗?
有。 让我们离开comp
孤单。 它可以保留为Comparator<FilePane>
。 我们需要做的是将其转换为Comparator<Node>
。
FXCollections.sort(list, convertSomeHow(comp));
我们如何转换它? 好了, sort()
将通过比较器Node
。 我们需要的比较器是FilePane
。 因此,我们所需要做的就是在其中进行转换,然后推迟进行comp
。 像这样:
FXCollections.sort(list, Comparator.comparing(node -> (FilePane) node, comp));
要么:
FXCollections.sort(list, Comparator.comparing(FilePane.class::cast, comp));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.