gpt4 book ai didi

kotlin - 使用密封类时,MutableSet 不会防止重复内容

转载 作者:行者123 更新时间:2023-12-02 08:43:21 24 4
gpt4 key购买 nike

如果我将 MutableSetsealed class 一起使用,则 MutableSet 接受所有重复的内容。

示例:

sealed class LoginSavedCommand {
class Login(val email: String, val password: String) : LoginSavedCommand()
class SaveData(val email: String, val password: String) : LoginSavedCommand()
}

fun main(args: Array<String>) {

val mSet: MutableSet<LoginSavedCommand> = hashSetOf()

mSet.add(LoginSavedCommand.Login("oba", "pass"))
mSet.add(LoginSavedCommand.Login("faiii", "blabla"))

if (mSet.add(LoginSavedCommand.Login("oba", "pass"))) {
println("don't")
} else {
println("do")
}
}

我将相同的值传递给 LoginSavedCommand.Login,但 MutableSet 继续接受添加相同的值(在示例 println print "don't”,并且我需要打印“do”,因为我需要使用这个selaed class来防止重复的内容)

最佳答案

MutableSet 使用元素的 equals checks 检查它是否包含元素。并且,根据实现情况,hashCode 。例如,HashSet 使用 hashCode 来存储并快速查找哈希表中的元素。

示例中的sealed class的两个子类不会覆盖equals函数,因此提供默认的相等性检查实现,即身份相等性(即对象只等于它自己,不同的对象即使属性相同也永远不会相等。

要实现 MutableSetLoginSavedCommand 项的唯一性,您需要确保子类提供正确的相等性检查实现。

<小时/>

一个简单的方法是 make both subclasses data classes ,以便编译器根据属性生成 equalshashCode 实现:

sealed class LoginSavedCommand {
data class Login(val email: String, val password: String) : LoginSavedCommand()
data class SaveData(val email: String, val password: String) : LoginSavedCommand()
}

(runnable sample)

<小时/>

或者,在子类中手动重写 equalshashCode 函数。

重要提示:覆盖这些函数时,请确保实现遵循 equals 的 API 引用中描述的函数约定。和 hashCode .

例如:

sealed class LoginSavedCommand {
class Login(val email: String, val password: String) : LoginSavedCommand() {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false

other as Login

if (email != other.email) return false
if (password != other.password) return false

return true
}

override fun hashCode(): Int {
var result = email.hashCode()
result = 31 * result + password.hashCode()
return result
}
}


class SaveData(val email: String, val password: String) : LoginSavedCommand() {
/* ... */
}
}

这些实现由 IntelliJ IDEA 使用类主体中的 Generate...equals() 和 hashCode() 操作生成。

关于kotlin - 使用密封类时,MutableSet 不会防止重复内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57467740/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com