我正在努力让这个工作:
实现方法countWhere(条件:(T(->Boolean(:Int。该方法返回满足条件(state(的元素数量。以下是如何使用的示例:
注意:我无法更改有趣的主要内容
fun main () {
val list = LinkedList <String> ()
list . addFirst ("Apple")
list . addFirst ("Banana")
list . addFirst ("Bear")
val fruitStartsWithB = list. countWhere {element ->
element. starts with ("B")
}
println (fruitStartsWithB) // fruitsStartsWithB is 2 because there are two items in the list that go into "B".
}
这就是给我带来麻烦的原因:
fun countWhere(condition: (T) -> Boolean): Int {
var count: Int = 0
forEach { if (this == condition) count++ }
return count
}
我的回报是0。我的回报必须是2。我的错误在哪里?我该如何纠正?
这是我所有的代码:
class LinkedList <T>: Iterable<T> {
data class Node <T>( val data : T, var next : Node <T>?)
private var first : Node <T>? = null
var isSorted = true
fun isEmpty() = first == null
fun addFirst(data: T) {
first = Node(data, first)
isSorted = false
}
fun getFirst(): T = get(0)
fun get(n: Int): T {
if (n < 0 ) throw IndexOutOfBoundsException ()
var run = first
var count = 0
while (count < n && run != null) {
run = run.next
count++
}
return run?.data ?: throw IndexOutOfBoundsException ()
}
fun clear () {
first = null // Clear
isSorted = true // Clear
}
// fun size (): Int{
// var run = first
// var count = 0
// while (run != null) {
// count++
// run = run.next
// }
// return count
// }
fun getOrNull(index: Int): T? {
if (index < 0 ) return null
var run = first
var count = 0
while (count < index && run != null) {
run = run.next
count++
}
return run?.data ?: null
}
fun addLast (data: T){
if (isEmpty()) addFirst(data) else {
var runPointer = first
while (runPointer?.next != null) {
runPointer = runPointer.next
}
runPointer?.next = Node(data, null)
}
isSorted = false
}
fun forEach(action: (T) -> Unit) {
for (i in this ) action(i)
}
fun size (): Int{
var count = 0
forEach { count ++ }
return count
}
override fun iterator(): Iterator<T> = object: Iterator <T> {
private var run = first
override fun hasNext(): Boolean = run!= null
override fun next(): T {
val res = run?.data ?: throw NoSuchElementException()
run = run?.next
return res
}
}
fun countWhere(condition: (T) -> Boolean): Int {
var count: Int = 0
forEach { if (condition(it)) count++ }
return count
}
}
您必须调用您的lambda:
fun countWhere(condition: (T) -> Boolean): Int {
var count: Int = 0
forEach { if (condition(it)) count++ }
return count
}