

In the following example, we are adding more planets to our list of planets using addAll method. We can use method addAll to add a list of elements to array list. Pluto Adding elements to an existing ArrayList In the following example, we are iterating through array list of planets and printing each planet. We can use for loop to iterate through an arraylist in Kotlin. Var planets = arrayListOf("Mercury", "Venus", "Earth", "Pluto") In the following example, we are creating an arraylist with list of planets and then printing the arraylist. We created String theory of empty cosmos below. We can create an array list using arrayListOf builtin function. In this tutorial we will go through features of ArrayList in Kotlin. Val p2 = arrayOf(arrayOf(Person("John", 20), Person("Mary", 15)))Īssertions.assertTrue(p1 contentDeepEquals p2) 6.ArrayList provides implementation for MutableList interface in Kotlin. Moreover, we can also validate the structural equality for nested arrays holding objects of Person type using the contentDeepEquals function: data class Person (var name: String?, var age: Int?) We can solve this problem by defining the Person class as a data class: data class Person (var name: String?, var age: Int?)Īssertions.assertTrue(first contentEquals second)Īs a data class inherently defines the equals() method for value comparison, we can assert that the first and second arrays containing objects of Person type are structurally equal.

That’s because we haven’t defined the equals() method in the Person class, and as a result, the contentEquals function is, by default, doing a referential equality check. Val second = arrayOf(Person("John", 20), Person("Mary", 15))įor such scenarios, the contentEquals function won’t be able to make a structural comparison of the arrays: Assertions.assertFalse(first contentEquals second) Val first = arrayOf(Person("John", 20), Person("Mary", 15))

Let’s define a Person class and initialize two arrays that contain instances of the Person class: class Person (var name: String?, var age: Int?) Now, let’s go ahead and expand our understanding to compare arrays that contain user-defined objects. So far, we’ve seen array comparisons for String values.
