You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

合并两类不同对象的列表按日期排序出现类型不匹配错误如何解决

报错根因
  • 你声明的合并列表类型为List<Object>,但自定义的CustomComparator仅支持比较实现了CustomInterface的类,Object不符合泛型约束,因此触发类型匹配错误
  • 代码存在两处拼写错误:一是compare方法的第一个参数声明漏写空格,写成了CustomInterfacet1;二是调用排序时把比较器类名写错为CustomComprator,缺失了字母a
修复方案
  1. 将合并列表的泛型从Object改为CustomInterface,A和B都实现了该接口,类型完全兼容
  2. 修正所有拼写错误
  3. 建议将方法返回值调整为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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 13:57:06