Search code examples
javaarrayslistkotlindynamic-arrays

Initialise ArrayList<ArrayList<Int>> with a size in kotlin


I am trying to initialise a list with a size in the constructor. But the size of my list is 0.

val seqList = ArrayList<ArrayList<Int>>(N) // This has the Problem
val queries = ArrayList<Query>(Q) // This works like a charm

I have both N and Q set as non zero inputs from the user lets say N = 100 and Q = 100

While debugging my code I found out that, queries.size() = 100 but seqList.size() = 0

Is my assumption incorrect, that seqList should also have been initialized with N ArrayList<Int> objects.


Solution

  • Your assumption isn't correct, I'm afraid.

    Quoted from the documentation of ArrayList:

    Provides a MutableList implementation, which uses a resizable array as its backing storage.

    This implementation doesn't provide a way to manage capacity, as backing JS array is resizeable itself. There is no speed advantage to pre-allocating array sizes in JavaScript, so this implementation does not include any of the capacity and "growth increment" concepts.

    The constructor particularly:

    ArrayList(initialCapacity = 0))
    

    Creates an empty ArrayList.

    An empty ArrayList is created, thus providing 100 as an argument will not create elements inside the list.