如何从HashSet中获取()特定元素?科特林

Xfc*_*ce4 5 android hashset kotlin

认为 myHashSet = HashSet<SomeClass>

在哪里 SomeClass.hashcode() = someField.hashcode()

如何返回具有指定哈希码的元素,即:

myHashSet.getElementWithHashCode((other as SomeClass).someField.hashcode())
Run Code Online (Sandbox Code Playgroud)

other并且里面的对象HashSet是不同的对象,除了值之外,具有不同的属性值someField。换句话说,这两种不同类型的对象具有可能具有相同值的公共字段。

很奇怪,HashSet 中没有这样的函数。以前没人需要吗?最快的方法是什么?

Mal*_*wig 2

我不知道是否适用于您的情况,这取决于它是使用hashCode还是equals内部。一些有类似问题的在线资源正在寻找基于平等的解决方案。

find无论如何,您可以使用像或 这样的内置函数first自己实现它:

fun <E> HashSet<E>.findByHashCode(other: E): E? = firstOrNull { it.hashCode() == other.hashCode() }
Run Code Online (Sandbox Code Playgroud)