Arrays and Their Operations

Learn how to work with arrays, including creating, accessing elements, and performing various array operations.

Introduction to arrays

An array is a very basic data structure that strongly relates to how memory is organized. Our computer’s memory is like a big parking lot, where each place has a sequential number. An array is like a reservation for a number of adherent spaces. With such a reservation, it is really easy to iterate over the cars we own. It is also easy to find a car with a specific index.

  • Let’s say that an array starts at position 1024 in our memory, and we need to find the element at index 100 in the array.

  • We also know that each element takes 4 positions (an array reserves constant space for its elements, which in most cases is the size of the memory reference).

  • This is an easy problem: our element starts at the position 1024 + 100 * 4 = 1424.

Advantages

  • Accessing an element at a certain position is a very simple and efficient operation, which is a big advantage of using arrays.

  • Arrays are used by many other data structures under the hood. For instance, when we use mutableListOf on Kotlin/JVM, the result object is ArrayList, which keeps elements in an array. This is why finding an element at an index in the default list is so efficient. So, ArrayList has the advantages of arrays, but it offers much more.

  • Arrays have a constant size, so we cannot add more elements than their size allows. When we add an element to an ArrayList and its internal array is full already, it creates a bigger one and fills it with the previous values.

Working with arrays

Arrays are also used by the default Set and Map that we use in Kotlin. Both are based on a hash table algorithm that needs to use an array to work efficiently. Nevertheless, let’s see how arrays can be used directly.

  • We create an array using the arrayOf function. This creates an instance of class Array and of type Array<T>, where T is the type of the elements.

  • To get an element at a certain index, we can use [] brackets or the get method.

  • To modify an element at a certain position, we can use [] brackets or the set method.

  • We can also get an array’s size using the size property or by iterating over the array using a for loop.

Get hands-on with 1200+ tech skills courses.