我所做的代码不能用于收集。还有其他方法来排序对象数组列表吗?或者如何使用collection。sort进行排序?
Object [] objects = BookAnalyser.array.toArray();
ArrayList<Object> uniqueword = new ArrayList<Object>();
for (Object h: BookAnalyser.WordList.findUnique(objects, objects)){
if(h != null ) {
uniqueword.add(h);
}
}
Collections.sort((uniqueword)); //Error: The method sort(List<T>) in the type Collections is not applicable for the arguments (ArrayList<Object>)
for(Object j : uniqueword) {
System.out.print(j+ " ");
}
显示了Collections类型中的sort(List)方法不适用于参数(ArrayList)。正常情况下是可以的。
您正在尝试排序List<T>
,其中T
是Object
。
Collections.sort
的定义为
static <T extends Comparable<? super T>> void sort(List<T> list)
表示类型参数必须实现Comparable<? super T>
,而Object
不实现。
两个解决方案:
- 让
uniqueword
成为Comparable
的列表,例如String
- 提供您自己的自定义
Comparator<Object>
,但您必须向下cast到可以比较的东西,所以第一个选项(例如List<String>
)是首选。