The Programmers Guide To Kotlin - Collections |
Written by Mike James | |||
Monday, 24 February 2020 | |||
Page 2 of 2
You can create a MutableList in the same way as a List: var a:MutableList<String> = mutableListOf("x","y","z") var b = MutableList<String>(10,{i->(i.toString())}) The big difference is that you can make the MutableList bigger. If you are familiar with more permissive languages such as JavaScript you might think that this allows you to reference elements that don't exist. You can't. To add an element beyond what are already there you have to use the add method: var a:MutableList<String> = mutableListOf("x","y","z") a.add("k") which produces ["x","y","z","k"]. The add method adds to the end of the collection by default, but you can insert an element at a specific position. For example: var a:MutableList<String> = mutableListOf("x","y","z") a.add(1,"k") produces ["x","k","y","z"] You can also use the addAll method to add a list of elements in one go. To shrink the collection you can use remove and clear which remove one instance of an element and all of the elements respectively. The sublist(start,end) method gives you the ability to extract a sub-list. Unlike other languages there is no support for "slicing notation". It is important that you don't try to make use of an element that doesn't exist. If you do, the result is a run-time exception. You can check the size of a collection using the size property and the lastindex property. As well as these basic methods and properties there are a number of extensions that take us well beyond what is available in Java. Notable are the sorting methods, the binary search method, and a set of methods that let you find and count elements. They are all worth knowing about and very straightforward in their use. As already mentioned List isn't completely immutable. For example, if you explicitly cast to MutableList then you can change elements: var a=listOf("x","y","z") var b:MutableList<String> b=a as MutableList<String> b[1]="k" println(a) This results in [x,k,z] being printed and immutable List a has been changed. If you want a List to be immutable make sure it isn't cast to MutableList. The CollectionsThe List a good archetypal collection class, but what else do we have? As in Java there are three types of collection:
The List has already been described, and it is an ordered list of elements much like an array. A Map is a set of key value pairs, sometimes called a dictionary, hash map or associative array in other languages. A Set is an unordered list which allows you to store values in it as if it was a simple container. The key feature of a Set is that it doesn't allow duplicates. Let's take a brief look at maps and sets. MapMap<K, out V> MutableMap<K, V> Map is one of the most useful collection objects and most sophisticated. You can store a set of key/value pairs and retrieve and store values using the key. Key values have to be unique, and you can only store one value per key. The key is covariant in Map and both types are invariant in MutableMap. Creating an instance of Map works in the same general way, but there are no constructors. Instead you have to use the mapOf and mutableMapOf builder functions, which create objects that implement the Map or MutableMap interfaces. For example: var a=mapOf("a" to 1,"b" to 2) The to operator is a function that converts the left and right objects into a key/value Pair. You can create your own Pair objects and use them in mapOf if you want to: var e=Pair("c",3) var a=mapOf("a" to 1,"b" to 2, e) To access an element you can use the get(K) and put(K,V) methods. You can also set up a map using: var b= mutableMapOf<String,Int>() b.put("a",1) and so on. SetSet<out E> MutableSet<E> Set is an unordered collection that doesn't allow duplicates. As in the case of Map you cannot call a constructor to create a Set. Instead, there are builder functions setOf and mutableSetOf. For example: var a=setOf<String>("a","b","c") You can use add(E) and remove(E) to add and remove elements. The only real reason for building and using a set is to keep track of which elements are in it. To do this you generally use the contains(E) method which is common to all collections. An alternative way of creating a set is: var a= mutableSetOf<String>() a.add("a") If you try and add the same element more than once then you don't generate an exception, but there is still only one instance stored in the set. In addition to Kotlin supported collection types List, Map and Set, there are also type aliases for the Java types ArrayList, HashMap, HashSet, LinkedHashMap, LinkedHashSet and RandomAccess. These are essentially different implementations of the same collection types and work in the same way. Also notice that currently the Kotlin List is implemented as a Java ArrayList. Sections not included in this extract:
Summary
This article is an extract from: Programmer's Guide To Kotlin Third Edition
You can buy it from: Amazon Contents
<ASIN:B0D8H4N8SK> To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.
Comments
or email your comment to: comments@i-programmer.info <ASIN:1871962536> <ASIN:1871962544>
|
|||
Last Updated ( Monday, 24 February 2020 ) |