Home > OS >  How can I create an ArrayList of n elements in Kotlin?
How can I create an ArrayList of n elements in Kotlin?

Time:10-28

This should be trivial. Kotlin has an ArrayList with a constructor "initialCapacity"

If I have this test case;

class ArrayListTest : TestCase() {

  @Test
  fun testArrayList() {
      val test = ArrayList<Int>(12)
      test[3]=5
  }
}

I get the exception java.lang.IndexOutOfBoundsException: Index 3 out of bounds for length 0

Running in debug confirms that although the ArrayList is created, its size is zero.

The docs say there's limited functionality for controlling capacity because the backing array is resizable itself, but this doesn't seem to be happening. Even if I use index 0 I get the out of bounds exception.

I tried running an update on the offchance. I'm running Android Studio Arctic Fox 2020.3.1 Patch 3, of Oct 1st 2021.

Has anyone else encountered and resolved this?

Edit: hmm. test.add(5) lets you append, which is fine for most cases. I'm leaving the question up because it seems the original approach should work.

CodePudding user response:

The constructor that takes an initialCapacity parameter only uses the capacity as the size of the backing array under the hood. Note the parameter is called "capacity", not "size". This is useful if you know ahead of time that the list will likely not grow beyond a certain size, because then it doesn't use a bigger backing array than necessary, and it won't have to resize the array later if it started too small.

Unlike Array, ArrayList has no fixed size. Its size is dependent on what elements are currently in it. So it always starts with size zero unless you pass elements to its constructor.

You created an ArrayList with size zero and backing array capacity of 12. Since it has zero elements, you can't access an element with index bigger than its size.

You seem to want to create an ArrayList with a specific size, all filled with zeroes. There's no function or constructor for doing that exactly, but you can do it with MutableList like this:

val test = MutableList(12) { 0 }
  • Related