
walkmc.collections.LimitedList.kt Maven / Gradle / Ivy
package walkmc.collections
/**
* Represents a limited list. A limited list only can have specified [limit] of elements.
*/
open class LimitedList(
var limit: Int,
private val delegate: MutableList = ArrayList()
) : MutableList by delegate {
/**
* Adds the specified element to the end of this list.
*
* @return false if the size of this list is reached to [limit], otherwise, true
*/
override fun add(element: T): Boolean {
if (size >= limit)
return false
return delegate.add(element)
}
/**
* Inserts an element into the list at the specified [index].
*/
override fun add(index: Int, element: T) {
if (index >= limit)
return
delegate.add(index, element)
}
/**
* Adds all of the elements of the specified collection to the end of this list.
*
* The elements are appended in the order they appear in the elements collection.
*/
override fun addAll(elements: Collection): Boolean {
if (size >= limit)
return false
return delegate.addAll(elements.take(limit - size))
}
}
/**
* Creates a empty limited list.
*/
fun limitedListOf(limit: Int) = LimitedList(limit)
/**
* Creates a limited list by [elements].
*/
fun limitedListOf(limit: Int, vararg elements: T) = LimitedList(limit, elements.toMutableList())
/**
* Converts this mutable list to a limited list.
*/
fun MutableList.toLimitedList(limit: Int) = LimitedList(limit, subList(0, limit))
/**
* Converts this iterable to a limited list.
*/
fun Iterable.toLimitedList(limit: Int): LimitedList =
if (this is MutableList) this.toLimitedList(limit) else toMutableList().toLimitedList(limit)
© 2015 - 2025 Weber Informatics LLC | Privacy Policy