我有一个使用番石榴的Lists.transform函数转换的列表。稍后,当我尝试使用Collections.sort()对列表进行排序时,我会得到一个UnsupportedOperationException。
我的代码是这样的:
private List<SelectItemInfo> convertToSelectItemList(
final List<String> dataOwnersOfActiveQualifiers)
{
final List<SelectItemInfo> dataOwnersSelectItemList = transform(dataOwnersOfActiveQualifiers,
new Function<String, SelectItemInfo>()
{
public SelectItemInfo apply(final String input)
{
final Employee employee = getLdapQuery().findEmployeesByIdOrLogin(input);
return new SelectItemInfo(input, employee.toStringNameSurname());
}
});
Collections.sort(dataOwnersSelectItemList, this.comparator);
return dataOwnersSelectItemList;
}我不知道为什么我会犯这个错误。
发布于 2018-10-30 14:12:39
Collections.sort需要能够调用列表中的set并让它完成预期的事情。transform返回的列表不支持它的set方法(它是一个“只读”列表)。
一个简单的解决方法是创建一个新的列表并对其进行排序
List<SelectItemInfo> sortedCopy = new ArrayList(dataOwnersSelectItemList);
Collections.sort(sortedCopy, this.comparator);
// use sortedCopy流是一个更好的解决方案。
https://stackoverflow.com/questions/53065894
复制相似问题