带有项目列表的对象的Diffutils

问题描述

希望有人可以帮助我。如何将diffutils用于具有对象列表的对象。因此,举个简单的例子,可能没有任何意义,但要有一个更好的主意。

data class Exercise(
    val name: String,var sets: String,var bodyTarget: String,var weight: String,)


data class Workout(
    private val workOutId: String,private val date: String,private val exercises: MutableList<Exercise>
)

我的适配器数据是“锻​​炼”列表。因此,我不确定如何在运动课中比较运动。我想我需要在areContentsTheSame内逐一比较练习吗?还是有一种更简单的方法来完成此任务

class DiffUtilSample(
private val oldList: List<Workout>,private val newList: List<Workout>
) : DiffUtil.Callback(){

    override fun areItemsTheSame(oldItemPosition: Int,newItemPosition: Int): Boolean =
        oldList[oldItemPosition].workOutId == newList[newItemPosition].workOutId

    override fun getOldListSize(): Int = oldList.size

    override fun getNewListSize(): Int = newList.size

    override fun areContentsTheSame(oldItemPosition: Int,newItemPosition: Int): Boolean {
    //Compare the list of exercises from each workout one by one? So for example I'd compare 
    //the reps,bodyTarget,weight etc 
    }

}

任何帮助将不胜感激。谢谢!

解决方法

由于您比较了data classes,并且列表内的对象也是data class实例,因此您只需编写:

oldList[oldItemPosition] == newList[newItemPosition]

那是因为data class会自动为您覆盖等于。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...