DEV Community

Cover image for How to Initialize an ArrayList in Kotlin
Jeremy Grifski
Jeremy Grifski

Posted on • Originally published at therenegadecoder.com on

2 1

How to Initialize an ArrayList in Kotlin

For those of you familiar with the How to Python series, I thought it would be fun to try my hand at some other languages I’ve been using lately. Today, let’s learn how to initialize an ArrayList in Kotlin.

Problem Introduction

As someone who came from Java, I often find myself using the ArrayList class to store data. Unfortunately, there’s no clean way of initializing an ArrayList in Java, so I wondered if Kotlin had improved on that issue. For reference, here’s what I don’t want to do:

ArrayList<Integer> list = new ArrayList<Integer>()
list.add(7)
list.add(-4)
list.add(3)
Enter fullscreen mode Exit fullscreen mode

As you can probably imagine, this solution does not scale well. In fact, I don’t even think it reads well. There’s just too much redundant information. I would prefer to be able to do something like the following:

ArrayList<Integer> list = new ArrayList<Integer>(7, -4, 3)
Enter fullscreen mode Exit fullscreen mode

And, for larger data sets, it would be nice to be able to spread the values over multiple lines:

ArrayList<Integer> list = new ArrayList<Integer>( 
    7, -4, 3, 2, 1, 3, 6, 5, 9, 11, 
    10, 7, -5, -6, 13, 6, -11, 13, 2, 1
)
Enter fullscreen mode Exit fullscreen mode

Unfortunately, that’s just not the case. There are some nasty workarounds, but I was hoping Kotlin would improve on the Java conventions a bit.

Solutions

Fortunately, Kotlin has improved quite a bit on Java’s verbosity, so I promise there’s a better way to create an ArrayList. It’s just a matter of how.

Initializing an ArrayList by Brute Force

Naturally, we can translate the Java solution almost directly:

val list = ArrayList<Int>()
list.add(7)
list.add(-4)
list.add(3)
Enter fullscreen mode Exit fullscreen mode

Here, we’ve created an empty ArrayList of integers. Then, we populated that list one item at a time using the add() method.

Of course, we’d love something better than this! Let’s see what Kotlin has to offer.

Initializing an ArrayList by Conversion

One way to reduce some of the code from above is to create an Array before converting it into an ArrayList:

val list = intArrayOf(7, -4, 3).toCollection(ArrayList())
Enter fullscreen mode Exit fullscreen mode

In a single line of code, we’re able to create an array of integers using the ideal syntax. 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.

Obviously, this isn’t ideal as we have to convert between the two types. It would be much nicer to be able to create and initialize an ArrayList directly. Fortunately, we can!

Initializing an ArrayList with arrayListOf

As it turns out, the collections library includes a function for building an ArrayList in Kotlin directly:

val list = arrayListOf<Int>(7, -4, 3)
Enter fullscreen mode Exit fullscreen mode

I’m not totally sure how this method works under the hood, but I imagine it works similar to our brute force solution:

fun <T> arrayListOf(vararg elements: T): ArrayList<T> { 
    val list = ArrayList<T>() 
    for (element in elements) { 
        list.add(element) 
    } 
    return list
}
Enter fullscreen mode Exit fullscreen mode

In any case, we have a concise solution for building up an ArrayList. That’s exciting!

Performance

Since I got into the habit of measuring performance in Python, I thought I could transition that idea over to Kotlin. Fortunately, there is a standard function which will do just that: measureNanoTime. We’ll be using that to test each of the code snippets above:

import kotlin.system.measureNanoTime

val bruteForceTime = measureNanoTime { 
    val list = ArrayList<Int>() 
    list.add(7) 
    list.add(-4) 
    list.add(3)
}

val conversionTime = measureNanoTime { 
    val list = intArrayOf(7, -4, 3).toCollection(ArrayList())
}

val arrayListOfTime = measureNanoTime { 
    val list = arrayListOf<Int>(7, -4, 3)
}

println("Brute Force: $bruteForceTime")
println("Conversion: $conversionTime")
println("ArrayListOf: $arrayListOfTime")
Enter fullscreen mode Exit fullscreen mode

In my case, the brute force method was significantly faster than the other two methods, but I’m not sure how these functions scale with more input. Feel free to try and let me know. At any rate, here are the results:

Brute Force: 38700

Conversion: 14728800

ArrayListOf: 6319000

For this test, I ended up using measureNanoTime over measureTimeMillis because I kept getting a value of zero for the brute force method. Now, that makes sense!

For reference, I tested everything on Windows 10 using Android Studio to setup a scratch file called scratch.kts. Also, I used Kotlin 1.3.31.

A Little Recap

As always, here are all the solutions in one convenient place:

// Brute force
val list = ArrayList<Int>()
list.add(7)
list.add(-4)
list.add(3)

// Array conversion
val list = intArrayOf(7, -4, 3).toCollection(ArrayList())

// Direct method
val list = arrayListOf<Int>(7, -4, 3)
Enter fullscreen mode Exit fullscreen mode

Since I’m just starting to play with Kotlin, this may seem like a pretty trivial tutorial. That said, I guarantee I’ll start digging into more interesting topics. For instance, I’m already excited to start mirroring some of the Python articles.

While you’re here, why not support The Renegade Coder by becoming a member. You’ll get access to all kinds of fun articles like:

Of course, you’re welcome to just hop on the newsletter and decide at a later date. Either way, I appreciate the support.

The post How to Initialize an ArrayList in Kotlin appeared first on The Renegade Coder.

Hot sauce if you're wrong - web dev trivia for staff engineers

Hot sauce if you're wrong · web dev trivia for staff engineers (Chris vs Jeremy, Leet Heat S1.E4)

  • Shipping Fast: Test your knowledge of deployment strategies and techniques
  • Authentication: Prove you know your OAuth from your JWT
  • CSS: Demonstrate your styling expertise under pressure
  • Acronyms: Decode the alphabet soup of web development
  • Accessibility: Show your commitment to building for everyone

Contestants must answer rapid-fire questions across the full stack of modern web development. Get it right, earn points. Get it wrong? The spice level goes up!

Watch Video 🌶️🔥

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay