'What data type can save latest 20 values in Kotlin?
Is there a data type where I can save latest 20 values in it?
Maybe just like Code A
Code A
val myData: ADateType<Int>(20)
myData.add(1)
myData.add(2)
...
myData.add(20)
myData.add(21)
val result1=myData.getList //It will return 2,3,4,...20,21
myData.add(22)
myData.add(23)
val result2=myData.getList //It will return 4,5,6...22,23
Solution 1:[1]
collection don't have custom limite, but you can write a class to control the size of collection, like this
class ADateType<E>() {
private val mList = mutableListOf<E>()
private val mMaxSize = 20
fun add(element: E) {
if (mList.size>=mMaxSize)
mList.removeAt(0)
mList.add(element)
}
fun toList(): List<E> {
return mList.toList()
}
}
The result is someting like this
fun main() {
val list = ADateType<Int>()
list.add(1)
list.add(2)
...
list.add(20)
list.add(21)
list.add(22)
println(list.toList()) //It will return 3,4,5,6...21,22
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Fábio Machado |
