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
相关产品推荐
相关产品推荐

