...

/

Arrays and Their Operations

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 ...