我有以下类别,用于计算所有有序集合的集合:
class PowerSet<T>(val inputSet: List<T>, val minLength: Int = 4) {
private var combinations = mutableListOf<MutableList<T>>()
init {
powerset(listOf(), inputSet)
}
private fun <T> powerset(curr: List<T>, left: List<T>) {
if (curr.size > this.minLength) {
combinations.add(curr)
}
if (left.isEmpty()) {
return
}
for ((index, value) in left.withIndex()) {
val subList = left.subList(0, index) + left.subList(index + 1, left.size)
val newList = curr + listOf(value)
powerset(newList, subList)
}
}
}
发生以下错误:
Type mismatch.
Required:
MutableList<T#1 (type parameter of com.example.PowerSet)>
Found:
List<T#2 (type parameter of com.example.PowerSet.powerset)>
不知道为什么会这样。
这是因为您的方法powerset
具有自己的类型参数T
。
您应该删除<T>
那里,因为您希望T
和班级的一样T
:
private fun powerset(curr: List<T>, left: List<T>) {
// ...
}
然后,我认为您可能List
对vs也有疑问MutableList
。curr
是一个List<T>
,因此您不能将其添加到combinations
,因为它需要type的元素MutableList<T>
。
您可以使用toMutableList()
将转换List
为MutableList
:
combinations.add(curr.toMutableList())
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句