fun main() {
val list = listOf("B", "A", "A", "C", "B", "A")
print(findfrequency(list))
}
fun <T> findfrequency(list: T): MutableMap<String, Int> {
val frequencyMap: MutableMap<String, Int> = HashMap()
for (s in list) {
var count = frequencyMap[s]
if (count == null) count = 0
frequencyMap[s] = count + 1
}
return frequencyMap
}
问问题
53 次
2 回答
0
解决方法:不需要对变量列表进行泛型类型声明,只需添加<String>
函数参数即可。这是最终的程序:
fun main() {
val list_String = listOf("B", "A", "A", "C", "B", "A")
println(findfreq(list_String))
}
fun findfreq(list: List<String>): MutableMap<String, Int> {
val frequencyMap: MutableMap<String, Int> = HashMap()
for(i in list) {
var count = frequencyMap[i]
if(count == null) count = 0
frequencyMap[i] = count + 1
}
return frequencyMap
}
于 2021-04-09T05:54:12.957 回答
0
当你将一个字符串列表放入一个类型为 T 的函数中时,它的类型在运行时是未知的,你正试图迭代这个未知的类型。因此,您必须指明该对象可用于与之交互。
fun main() {
val list = listOf("B", "A", "A", "C", "B", "A")
print(findfrequency(list))
}
fun <T : Iterable<String>> findfrequency(list: T): MutableMap<String, Int> {
val frequencyMap: MutableMap<String, Int> = HashMap()
for (s in list) {
var count = frequencyMap[s]
if (count == null) count = 0
frequencyMap[s] = count + 1
}
return frequencyMap
}
在下面的示例中,我们不再像上面那样依赖 String 类型。但是,在输出中,我们会得到一个这种类型的 Map。
fun <T : Iterable<S>, S> findfrequency(list: T): MutableMap<S, Int> {
val frequencyMap: MutableMap<S, Int> = HashMap()
for (s in list) {
var count = frequencyMap[s]
if (count == null) count = 0
frequencyMap[s] = count + 1
}
return frequencyMap
}
于 2021-04-09T07:45:52.220 回答