Lists

Lists are collections of indexed items. Lists support insertion and retrieval of items by their position. Besides the ArrayListclass, which is probably the most used implementation, the List interface is also implemented in the LinkedList class. The ArrayList class is usually the one you'll use because it offers retrieval of items by position in constant time, and doesn't have the memory overhead of an additional Node object for each item which the LinkedList has. The Kotlin library provides several methods for creating instances of List interfaces. You can create the immutable instance of a List by calling the listOf function. The function accepts a vararg parameter which can be used to initialize the list with items:

val superHeros = listOf("Batman", "Superman", "Hulk")

There is also the arrayListOf function:

val moreSuperHeros = arrayListOf("Captain America", "Spider-Man")

If you are looking at the implementation of these methods, you might think that they are redundant, since both of them return an instance of the ArrayList class. The classes have the same name, but slightly different implementation. The one returned from the listOf function is a private class defined in the java.util.Arrays package. This is the same one you would get if you called the Arrays.asList function in Java. The arrayListOf function returns the “real” ArrayList class from the java.util package.

If you want to construct a mutable version of a List, there is the mutableListOf function:

val superHeros = mutableListOf("Thor", "Daredevil", "Iron Man")

This one can be modified as follows where the add method is defined in this version:

superHeros.add("Wolverine")

There is also the emptyList method which returns a read-only list with no items:

val empty = emptyList<String>()
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.131.38.14