MST

星途 面试题库

面试题:Kotlin约定机制下集合相关的约定实现

在Kotlin中,集合类有一些基于约定机制的特性。请描述如何实现一个自定义类,使其能够像Kotlin标准集合类一样支持`for - in`循环遍历,以及`get`和`set`操作,假设该自定义类用于存储一组整数。
33.0万 热度难度
编程语言Kotlin

知识考点

AI 面试

面试题答案

一键面试
  1. 实现 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()
}
  1. 实现 getset 操作
    • 对于 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
    }
}
  1. 使用示例
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 循环,同时重载了 getset 运算符来支持类似集合的获取和设置元素操作。并且在 main 函数中展示了这些操作的使用。