Skip to content Skip to sidebar Skip to footer

If We Alter the Object in the List Do We Have to Set It to the List Again Java

Collections overview

The Kotlin Standard Library provides a comprehensive set of tools for managing collections – groups of a variable number of items (possibly zero) that are meaning to the problem being solved and are commonly operated on.

Collections are a common concept for most programming languages, and so if you're familiar with, for example, Java or Python collections, you tin can skip this introduction and proceed to the detailed sections.

A drove usually contains a number of objects (this number may also exist zero) of the aforementioned type. Objects in a drove are chosen elements or items. For instance, all the students in a department class a collection that can be used to calculate their average age.

The following collection types are relevant for Kotlin:

  • List is an ordered collection with admission to elements past indices – integer numbers that reverberate their position. Elements can occur more than once in a list. An case of a list is a telephone number: it's a group of digits, their social club is important, and they can repeat.

  • Set is a collection of unique elements. It reflects the mathematical abstraction of set: a group of objects without repetitions. Generally, the lodge of set elements has no significance. For example, the numbers on lottery tickets grade a set: they are unique, and their order is not important.

  • Map (or dictionary) is a ready of primal-value pairs. Keys are unique, and each of them maps to exactly one value. The values can be duplicates. Maps are useful for storing logical connections between objects, for instance, an employee'due south ID and their position.

Kotlin lets you manipulate collections independently of the exact blazon of objects stored in them. In other words, you lot add a String to a list of Stringsouth the aforementioned style as you would do with Ints or a user-divers grade. So, the Kotlin Standard Library offers generic interfaces, classes, and functions for creating, populating, and managing collections of any type.

The collection interfaces and related functions are located in the kotlin.collections parcel. Let's get an overview of its contents.

Collection types

The Kotlin Standard Library provides implementations for bones collection types: sets, lists, and maps. A pair of interfaces represent each collection type:

  • A read-only interface that provides operations for accessing collection elements.

  • A mutable interface that extends the corresponding read-only interface with write operations: adding, removing, and updating its elements.

Note that altering a mutable collection doesn't require it to be a var: write operations modify the aforementioned mutable collection object, and so the reference doesn't change. Although, if y'all try to reassign a val drove, you'll become a compilation fault.

fun main() { //sampleStart val numbers = mutableListOf("i", "2", "three", "four") numbers.add("five") // this is OK println(numbers) //numbers = mutableListOf("half dozen", "seven") // compilation error //sampleEnd }

The read-simply collection types are covariant. This ways that, if a Rectangle class inherits from Shape, you can utilize a List<Rectangle> anywhere the Listing<Shape> is required. In other words, the drove types have the aforementioned subtyping relationship every bit the chemical element types. Maps are covariant on the value type, just not on the key type.

In turn, mutable collections aren't covariant; otherwise, this would atomic number 82 to runtime failures. If MutableList<Rectangle> was a subtype of MutableList<Shape>, you lot could insert other Shape inheritors (for example, Circle) into information technology, thus violating its Rectangle type statement.

Below is a diagram of the Kotlin collection interfaces:

Collection interfaces hierarchy

Let'southward walk through the interfaces and their implementations. To larn about Collection, read the section below. To learn about List, Set, and Map, yous can either read the respective sections or watch a video by Sebastian Aigner, Kotlin Programmer Advocate:

Collection

Collection<T> is the root of the collection hierarchy. This interface represents the common behavior of a read-merely collection: retrieving size, checking particular membership, and then on. Collection inherits from the Iterable<T> interface that defines the operations for iterating elements. You can employ Collection as a parameter of a role that applies to different collection types. For more specific cases, use the Collection'south inheritors: Listing and Prepare.

fun printAll(strings: Collection<String>) { for(s in strings) print("$south ") println() } fun main() { val stringList = listOf("one", "ii", "ane") printAll(stringList) val stringSet = setOf("one", "two", "three") printAll(stringSet) }

MutableCollection<T> is a Drove with write operations, such as add and remove.

fun List<String>.getShortWordsTo(shortWords: MutableList<Cord>, maxLength: Int) { this.filterTo(shortWords) { it.length <= maxLength } // throwing away the manufactures val articles = setOf("a", "A", "an", "An", "the", "The") shortWords -= articles } fun master() { val words = "A long fourth dimension agone in a galaxy far far abroad".divide(" ") val shortWords = mutableListOf<String>() words.getShortWordsTo(shortWords, 3) println(shortWords) }

List

List<T> stores elements in a specified gild and provides indexed admission to them. Indices commencement from naught – the index of the first element – and go to lastIndex which is the (listing.size - 1).

fun chief() { //sampleStart val numbers = listOf("one", "two", "three", "4") println("Number of elements: ${numbers.size}") println("Tertiary element: ${numbers.get(2)}") println("Quaternary element: ${numbers[3]}") println("Alphabetize of element \"two\" ${numbers.indexOf("ii")}") //sampleEnd }

List elements (including nulls) tin duplicate: a list can comprise any number of equal objects or occurrences of a single object. 2 lists are considered equal if they have the same sizes and structurally equal elements at the same positions.

data class Person(var proper noun: String, var age: Int) fun main() { //sampleStart val bob = Person("Bob", 31) val people = listOf(Person("Adam", 20), bob, bob) val people2 = listOf(Person("Adam", 20), Person("Bob", 31), bob) println(people == people2) bob.age = 32 println(people == people2) //sampleEnd }

MutableList<T> is a List with list-specific write operations, for example, to add or remove an chemical element at a specific position.

fun primary() { //sampleStart val numbers = mutableListOf(1, 2, 3, iv) numbers.add(five) numbers.removeAt(1) numbers[0] = 0 numbers.shuffle() println(numbers) //sampleEnd }

As you come across, in some aspects lists are very similar to arrays. However, there is one of import difference: an assortment's size is defined upon initialization and is never inverse; in plough, a list doesn't accept a predefined size; a listing's size can be changed as a event of write operations: adding, updating, or removing elements.

In Kotlin, the default implementation of List is ArrayList which you can think of as a resizable array.

Ready

Gear up<T> stores unique elements; their order is more often than not undefined. null elements are unique as well: a Ready can contain only 1 zippo. Ii sets are equal if they take the same size, and for each element of a prepare there is an equal element in the other set.

fun main() { //sampleStart val numbers = setOf(ane, 2, iii, four) println("Number of elements: ${numbers.size}") if (numbers.contains(i)) println("1 is in the set") val numbersBackwards = setOf(4, 3, 2, 1) println("The sets are equal: ${numbers == numbersBackwards}") //sampleEnd }

MutableSet is a Set with write operations from MutableCollection.

The default implementation of SetLinkedHashSet – preserves the order of elements insertion. Hence, the functions that rely on the order, such as outset() or final(), return predictable results on such sets.

fun master() { //sampleStart val numbers = setOf(1, 2, 3, iv) // LinkedHashSet is the default implementation val numbersBackwards = setOf(4, iii, two, i) println(numbers.kickoff() == numbersBackwards.first()) println(numbers.beginning() == numbersBackwards.last()) //sampleEnd }

An alternative implementation – HashSet – says aught about the elements order, and then calling such functions on it returns unpredictable results. However, HashSet requires less memory to store the same number of elements.

Map

Map<M, V> is not an inheritor of the Drove interface; however, it's a Kotlin drove blazon also. A Map stores key-value pairs (or entries); keys are unique, just different keys can be paired with equal values. The Map interface provides specific functions, such equally access to value by cardinal, searching keys and values, and then on.

fun main() { //sampleStart val numbersMap = mapOf("key1" to 1, "key2" to 2, "key3" to 3, "key4" to 1) println("All keys: ${numbersMap.keys}") println("All values: ${numbersMap.values}") if ("key2" in numbersMap) println("Value past cardinal \"key2\": ${numbersMap["key2"]}") if (one in numbersMap.values) println("The value one is in the map") if (numbersMap.containsValue(one)) println("The value one is in the map") // aforementioned equally previous //sampleEnd }

Two maps containing the equal pairs are equal regardless of the pair order.

fun main() { //sampleStart val numbersMap = mapOf("key1" to 1, "key2" to 2, "key3" to iii, "key4" to ane) val anotherMap = mapOf("key2" to two, "key1" to 1, "key4" to 1, "key3" to 3) println("The maps are equal: ${numbersMap == anotherMap}") //sampleEnd }

MutableMap is a Map with map write operations, for case, you can add together a new key-value pair or update the value associated with the given key.

fun main() { //sampleStart val numbersMap = mutableMapOf("ane" to i, "two" to two) numbersMap.put("three", three) numbersMap["ane"] = 11 println(numbersMap) //sampleEnd }

The default implementation of MapLinkedHashMap – preserves the guild of elements insertion when iterating the map. In plough, an alternative implementation – HashMap – says naught nearly the elements gild.

Last modified: x Dec 2021

justicehaverm.blogspot.com

Source: https://kotlinlang.org/docs/collections-overview.html

Post a Comment for "If We Alter the Object in the List Do We Have to Set It to the List Again Java"