Home > Enterprise >  What data type can save latest 20 values in Kotlin?
What data type can save latest 20 values in Kotlin?

Time:01-19

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

CodePudding user response:

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
}

CodePudding user response:

The standard library doesn’t have a class specifically for this. You can use CircularFifoQueue from Apache Commons Collections.

Here’s a basic tutorial.

Or here's a basic implementation of a CircularList. I haven't tested it thoroughly.

class CircularList<T> private constructor(maxSize: Int, private val backingList: LinkedList<T>) :
    MutableList<T> by backingList {

    constructor(maxSize: Int) : this(maxSize, LinkedList())

    var maxSize: Int = maxSize
        set(value) {
            field = value
            enforceSize()
        }

    private fun enforceSize() {
        repeat(backingList.size - maxSize) {
            backingList.removeFirst()
        }
    }

    override fun add(element: T): Boolean {
        backingList.add(element)
        enforceSize()
        return true
    }

    override fun add(index: Int, element: T) {
        backingList.add(element)
        enforceSize()
    }

    override fun addAll(index: Int, elements: Collection<T>): Boolean {
        backingList.addAll(index, elements)
        enforceSize()
        return true
    }

    override fun addAll(elements: Collection<T>): Boolean {
        backingList.addAll(elements)
        enforceSize()
        return true
    }

    override fun equals(other: Any?): Boolean {
        return backingList == other
    }

    override fun hashCode(): Int {
        return backingList.hashCode()
    }

    override fun toString(): String {
        return backingList.toString()
    }
}
  •  Tags:  
  • Related