合并两类不同对象的列表按日期排序出现类型不匹配错误如何解决
报错根因
- 你声明的合并列表类型为
List<Object>,但自定义的CustomComparator仅支持比较实现了CustomInterface的类,Object不符合泛型约束,因此触发类型匹配错误 - 代码存在两处拼写错误:一是
compare方法的第一个参数声明漏写空格,写成了CustomInterfacet1;二是调用排序时把比较器类名写错为CustomComprator,缺失了字母a
修复方案
- 将合并列表的泛型从
Object改为CustomInterface,A和B都实现了该接口,类型完全兼容 - 修正所有拼写错误
- 建议将方法返回值调整为
List<CustomInterface>,更符合类型规范,后续使用时无需额外强转
修正后的代码示例
比较器代码
public class CustomComparator implements Comparator<CustomInterface> { @Override public int compare(CustomInterface t1, CustomInterface t2) { // 若日期字符串不是可按字典序排序的格式(比如yyyy-MM-dd HH:mm:ss),建议先转为日期类型再比较 return t1.getDate().compareTo(t2.getDate()); } }
合并排序方法代码
public List<CustomInterface> sortedAndMergedData(List<A> a, List<B> b) { List<CustomInterface> mergeList = new ArrayList<>(); mergeList.addAll(a); mergeList.addAll(b); Collections.sort(mergeList, new CustomComparator()); return mergeList; }
内容的提问来源于stack exchange,提问作者newplayer
相关产品推荐
相关产品推荐

