Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 516
droidchef Avatar asked Aug 13 '17 14:08

droidchef


People also ask

Can you initialize an ArrayList with size?

ArrayList inherits AbstractList class and implements List interface. ArrayList is initialized by a size, however the size can increase if collection grows or shrink if objects are removed from the collection.

How do you initialize an ArrayList in Kotlin?

Initializing an ArrayList by Conversion From that array, we can obtain an ArrayList using the toCollection() method and passing an empty ArrayList. The toCollection() method then populates the ArrayList with all the values in the array.

How do I get the size of an ArrayList in Kotlin?

To get size of Array in Kotlin, read the size property of this Array object. size property returns number of elements in this Array. We can also use count() function of the Array class to get the size.


1 Answers

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.

like image 114
s1m0nw1 Avatar answered Sep 18 '22 15:09

s1m0nw1