0
votes

I'm createing a generic ring buffer and I would like to use array list as internal storage for data and I'd like to allocate array list with defined capacity.

This is an example using Kotlin ArrayList:

class RingBuffer<T>(private val capacity: Int) {
    private var buffer = ArrayList<T>(initialCapacity = capacity)
}

When I compile the code, this error appears:

Kotlin: None of the following functions can be called with the arguments supplied: public final fun (): kotlin.collections.ArrayList /* = java.util.ArrayList / defined in kotlin.collections.ArrayList public final fun (p0: (MutableCollection<out T!>..Collection<T!>?)): kotlin.collections.ArrayList / = java.util.ArrayList / defined in kotlin.collections.ArrayList public final fun (p0: Int): kotlin.collections.ArrayList / = java.util.ArrayList */ defined in kotlin.collections.ArrayList

I've tried to use Java ArrayList:

import java.util.ArrayList
class RingBuffer<T>(private val capacity: Int) {
    private var buffer = ArrayList<T>(capacity)
}

In this case code compiles, but buffer has size=0, so array is not allocated.

So the question is how to create and then allocate ArrayList with default T values?

1
size is not the same as capacity. size is 0 because the list contains nothing, but the underlying array should still be allocated with its capacity = capacity. If you really want to set a default value you can use something like MutableList(capacity){ default } - gpunto
@gpunto thanks. This is works var buffer = MutableList<T?>(capacity) { null }. Do you know if it's possible to omit nullability, to make it like var buffer = MutableList<T>(capacity) { default(T) }. For example this default(T) is possible in C#, but I'm not sure if there is something similar in Kotlin or Java? - Vadim Sentiaev
Are you aware that Kotlin 1.4 (just released) adds a new ArrayDeque class? Maybe that does what you want? - gidds
@gidds yep, I know about ArrayDeque. I'm implementing some data strucrures in Kotlin just for fun, to learn the language and understand how to write stuff in ideomatic Kotlin. - Vadim Sentiaev
@VadimSentiaev That's great! (But I'll leave my comment, in case other readers don't know about it.) - gidds

1 Answers

0
votes

It's possible to do it this way:

class RingBuffer<T>(size: Int) {
    private var buffer = MutableList<T?>(size) { null }
}

This is fine to have nullable T? because read method will have this signature:

fun read(): T?