Kotlin 中列表和数组类型的区别

Listarray是 Kotlin 支持的两个流行的集合。根据定义,这两个集合都分配顺序内存位置。在本文中,我们将通过一个示例来演示这两种集合之间的区别。

属性大批列表
ImplementationArray 是使用Array<T>类实现的List<T> or MutableList<T> interfaces are used to implement a List in Kotlin
可变的Array<T>是可变的,即可以更改值。List<T> is immutable in nature. In order to create a mutable list, MutableList<T> interface needs to be used.
尺寸数组是固定大小的。它不能增加和减少大小。MutableList<T> do have 'add' and 'remove' functions in order to increase or decrease the size of the MutableList.
表现使用它可以获得更好的性能,因为数组针对不同的原始数据类型进行了优化,例如IntArray[]、DoubleArray[]使用它来更好地访问代码。由于大小本质上是动态的,因此具有良好的内存管理。

示例

在下面的示例中,我们将看到如何在 Kotlin 中声明数组和列表,以及如何操作它们的值。

fun main(args: Array<String>) {

   val a = arrayOf(1, 2, 3)

   //打印数组 a 的所有值
   println("数组包含:")
   a.forEach{
      println(it)
   }


   val names = listOf("stud1", "stud2", "stud3")

   //打印列表名称的所有值
   println("\nThe List contains: ")
   names.forEach {
      println(it)
   }


   var days: MutableList<String> = mutableListOf(
      "Monday", "Tuesday", "Wednesday",
      "Thursday", "Friday", "Saturday", "Sunday"
   )

   //打印 MutableList 列表的所有值
   println("\nGiven Mutable List contains:")
   days.forEach{
      print(it)
   }

   println("\n\nMutable List after modification:")
   days.forEach{
      print(it + ", ")
   }

}
输出结果

它将生成以下输出 -

数组包含:
1
2
3

The List contains:
stud1
stud2
stud3

Given Mutable List contains:
MondayTuesdayWednesdayThursdayFridaySaturdaySunday

Mutable List after modification:
Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday,