- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to create a mutable list with repeating elements in Kotlin?
A Mutable List is an interface and generic collection of elements. Once a collection is declared as mutable, it becomes dynamic and we can modify its data as per requirement. A mutable list grows automatically in size as we insert new elements into it. The Mutable List inherits form the Generic<T> class.
Example – Creating a Mutable List in Kotlin
In order to create a mutable list of repeating elements, we will be using Kotlin List(). By definition, it looks like this−
inline fun <T> List( size: Int, init: (index: Int) -> T ): List<T>
As we pass an initial default value, it creates a read only list of specified number of elements. In this List(), each element is calculated by calling the specified init function.
In this example, we will be using a Mutable List to create a list of the squares of the first 5 numbers.
fun main(args: Array<String>) { val squares = MutableList(5) { (it + 1) * (it + 1) } // printing the squares of first 5 elements println(squares) }
Output
It will produce the following output −
[1, 4, 9, 16, 25]
Example – Creating a Mutable List with Repeating Elements in Kotlin
In order to create a dummy mutable list, we can just modify the above piece of code with a dummy String. As a result, we will be getting a mutable list of repeating elements.
fun main(args: Array<String>) { val squares = MutableList(5) {"Dummy"} println(squares) }
Output
On execution, it will produce the following output −
[Dummy, Dummy, Dummy, Dummy, Dummy]
- Related Articles
- How to create a list in Kotlin?
- How to create a data frame in R with list elements?
- How to create an immutable class with mutable object references in Java?\n
- How to create a listView with a checkBox in Kotlin?
- C# program to create a List with elements from an array
- Program to create a list with n elements from 1 to n in Python
- How to build a string with no repeating character n separate list of characters? in JavaScript
- How to initialize List in Kotlin?
- How to create a filter list with JavaScript?
- How to convert a List to a Map in Kotlin?
- How to create a dictionary with list comprehension in Python?
- How to create a List with Constructor in C++ STL
- JavaScript construct an array with elements repeating from a string
- How to clone or copy a list in Kotlin?
- Python Program to Create a Linked List & Display the Elements in the List
