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

Android API16环境下如何排序ArrayList<someclass>?

兼容API16的ArrayList排序方案

嘿,这个问题我做旧版本Android兼容的时候也碰到过!你用的ArrayList.sort()方法确实是从API24才开始支持的,所以在API16环境下会报错。要解决这个问题,咱们换用Collections.sort()就搞定了——这个方法从很早的Java版本就存在,完全兼容API16及更低版本。

具体实现代码

把你原来的代码替换成下面这样就行:

Collections.sort(items, new Comparator<someclass>() {
    @Override
    public int compare(someclass item1, someclass item2) {
        // 这里建议加个null值判断,避免出现空指针异常
        if (item1.Name == null && item2.Name == null) {
            return 0;
        }
        if (item1.Name == null) {
            return -1; // 可以根据需求调整,把null值排到前面或后面
        }
        if (item2.Name == null) {
            return 1;
        }
        return item1.Name.compareTo(item2.Name);
    }
});

关键提醒

排序完成后,一定要调用Adapter的notifyDataSetChanged()方法,这样才能让列表视图刷新,展示排序后的结果:

yourCustomAdapter.notifyDataSetChanged();

可选简化(如果项目支持)

要是你的项目配置了Java 8+的Lambda支持(比如借助Retrolambda插件),还能把代码简化成更清爽的形式:

Collections.sort(items, (item1, item2) -> {
    if (item1.Name == null && item2.Name == null) return 0;
    if (item1.Name == null) return -1;
    if (item2.Name == null) return 1;
    return item1.Name.compareTo(item2.Name);
});

内容的提问来源于stack exchange,提问作者ZeroKat

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:30:38