面试题答案
一键面试- 实现
Iterable
接口以支持for - in
循环遍历:- 要让自定义类支持
for - in
循环,需要实现Iterable
接口,并提供一个iterator
方法。 - 例如,假设自定义类名为
MyIntCollection
,它内部使用MutableList
来存储整数:
- 要让自定义类支持
class MyIntCollection : Iterable<Int> {
private val data = mutableListOf<Int>()
override fun iterator(): Iterator<Int> = data.iterator()
}
- 实现
get
和set
操作:- 对于
get
操作,可以通过重载get
运算符来实现。 - 对于
set
操作,通过重载set
运算符来实现。
- 对于
class MyIntCollection : Iterable<Int> {
private val data = mutableListOf<Int>()
override fun iterator(): Iterator<Int> = data.iterator()
operator fun get(index: Int): Int = data[index]
operator fun set(index: Int, value: Int) {
data[index] = value
}
}
- 使用示例:
fun main() {
val myCollection = MyIntCollection()
myCollection.add(1)
myCollection.add(2)
for (element in myCollection) {
println(element)
}
println(myCollection[0])
myCollection[0] = 10
println(myCollection[0])
}
在上述代码中,MyIntCollection
类实现了 Iterable
接口以支持 for - in
循环,同时重载了 get
和 set
运算符来支持类似集合的获取和设置元素操作。并且在 main
函数中展示了这些操作的使用。