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

Kotlin中如何交换MutableList内指定索引位置的元素?

实现方案

你只需要在返回筛选后的列表前,增加边界判断后交换索引0和1的元素即可,不需要修改原有筛选逻辑。交换操作有两种常用实现方式:

1. 原生手动交换(无额外依赖,兼容性最好)

直接通过临时变量赋值完成交换,搭配边界判断避免数组越界,修改后的完整代码如下:

fun MovieListDto.MovieListDtoToMovieList(): List<Movie> {
    val movieList = mutableListOf<Movie>()

    for (movie in docs) {
        if (movie._id == "5cd95395de30eff6ebccde5c" ||
            movie._id == "5cd95395de30eff6ebccde5b" ||
            movie._id == "5cd95395de30eff6ebccde5d"
        ) {
            movieList.add(movie)
        }
    }
    // 新增交换逻辑,先判断列表长度避免越界
    if (movieList.size >= 2) {
        val temp = movieList[0]
        movieList[0] = movieList[1]
        movieList[1] = temp
    }
    return movieList
}

2. 封装通用交换扩展(复用性更高)

如果后续有其他位置的交换需求,可以封装一个通用的MutableList扩展方法,自带边界判断更安全:

// 通用交换扩展方法
fun <T> MutableList<T>.swap(index1: Int, index2: Int) {
    if (index1 in indices && index2 in indices) {
        val temp = this[index1]
        this[index1] = this[index2]
        this[index2] = temp
    }
}

// 原有转换方法直接调用即可
fun MovieListDto.MovieListDtoToMovieList(): List<Movie> {
    val movieList = mutableListOf<Movie>()

    for (movie in docs) {
        if (movie._id == "5cd95395de30eff6ebccde5c" ||
            movie._id == "5cd95395de30eff6ebccde5b" ||
            movie._id == "5cd95395de30eff6ebccde5d"
        ) {
            movieList.add(movie)
        }
    }
    // 直接调用扩展方法完成交换
    movieList.swap(0, 1)
    return movieList
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 22:15:03