我使用下面的方法调用来返回对象列表。如何编写比较器来在Java中概括两种类型的对象?
final List<LinkModelSpi> documentLinks = this.documentLinksModelSpi.getDocumentLinks();
接下来我使用了Comparator
对这个列表进行排序。但List包含两种类型的对象。有些功能的工作原理是返回DocumentLinkModelImpl和一些功能操作它返回LinkModelImpl。所以,比较函数传递类转换异常时LinkModelImple变化DocumentLinkModelImpl两个对象父类型。这也顺从。
// Add This method for Sorting Document Link View Same Order. Now The application display same links order
// in catalogue administration edit drug window
Collections.sort(documentLinks,
(Comparator<? super LinkModelSpi>) new Comparator<DocumentLinkModelImpl>() {
@Override
public int compare(DocumentLinkModelImpl o1, DocumentLinkModelImpl o2) {
return o1.getResource().compareTo(o2.getResource());
}
/*@Override
public int compare(LinkModelImpl o1,LinkModelImpl o2) {
return o1.getResource().compareTo(o2.getResource());
}*/
});
我需要一些专家的帮助来解决这个问题吗?
注意: 我新增了上面的sort方法,但是在我添加之前,该方法对所有对象都执行得很好。
final List<LinkModelSpi> documentLinks = this.documentLinksModelSpi.getDocumentLinks();
for (final LinkModelSpi documentLinkModelSpi : documentLinks)
{
//noinspection unchecked
((DtoPresentationModelSpi<?, MDTO>) documentLinkModelSpi).addPropertyChangeListener(this);
}
--------------错误----------------------
Presentation.impl.LinkModelImpl cannot be cast to Presentation.impl.DocumentLinkModelImpl
at Client.catadmin.view.component.AbstractEditLinkDialog$1.compare(AbstractEditLinkDialog.java:171)
at java.util.TimSort.countRunAndMakeAscending(TimSort.java:355)
at java.util.TimSort.sort(TimSort.java:220)
您的'DocumentLinkModelImpl'是'LinkModelSpi'的子类型,并且查看您注释掉的代码,getResource函数在'LinkModelSpi'上可用 - 那么为什么不制作比较器仅用于'LinkModelSpi'?它可以用于* LinkModelSpi的* any *子类型,包括'DocumentLinkModelImpl'。 –
但先生它通过错误。我会将错误添加到问题 – uma