List型和Array型的区别是什么

val names1 = listOf("Joe","Ben","Thomas")
val names2 = arrayOf("Joe","Ben","Thomas")

for (name in names1)
    println(name)
for (name in names2)
    println(name)

推荐答案

Arrays and lists (represented by List<T> and its subtype MutableList<T>) have many differences, here are the most significant ones:

  • Array<T>是一个具有已知实现的类:它是一个顺序固定大小的内存区域,存储项目(在JVM上,它由Java array表示).

    List<T> and MutableList<T> are interfaces which have different implementations: ArrayList<T>, LinkedList<T> etc. Memory representation and operations logic of lists are defined in concrete implementation, e.g. indexing in a LinkedList<T> goes through the links and takes O(n) time whereas ArrayList<T> stores its items in a dynamically allocated array.

    val list1: List<Int> = LinkedList<Int>()
    val list2: List<Int> = ArrayList<Int>()
    
  • Array<T>是可变的(可以通过对它的任何引用进行更改),但List<T>没有修改方法(它是read-only view of MutableList<T>immutable list implementation).

    val a = arrayOf(1, 2, 3)
    a[0] = a[1] // OK
    
    val l = listOf(1, 2, 3)
    l[0] = l[1] // doesn't compile
    
    val m = mutableListOf(1, 2, 3)
    m[0] = m[1] // OK
    
  • 数组的大小是固定的,不能扩展或收缩(需要复制数组才能调整大小).至于列表,MutableList<T>addremove个函数,因此它可以增加和减少其大小.

    val a = arrayOf(1, 2, 3)
    println(a.size) // will always be 3 for this array
    
    val l = mutableListOf(1, 2, 3)
    l.add(4)
    println(l.size) // 4
    
  • Array<T>invariant on T(Array<Int>不是Array<Number>),与MutableList<T>相同,但List<T>是协变的(List<Int>List<Number>).

    val a: Array<Number> = Array<Int>(0) { 0 } // won't compile
    val l: List<Number> = listOf(1, 2, 3) // OK
    
  • 数组针对原语进行了优化:有单独的IntArrayDoubleArrayCharArray等映射到Java原语数组(int[]double[]char[]),而不是boxed个(Array<Int>映射到Java的Integer[]).列表通常没有针对原语优化的实现,尽管一些库(JDK之外)提供了原语优化列表.

  • List<T> and MutableList<T> are mapped types and have special behaviour in Java interoperability (Java's List<T> is seen from Kotlin as either List<T> or MutableList<T>). Arrays are also mapped, but they have other rules of Java interoperability.

  • annotations中使用某些数组类型(基元数组、Array<String>和具有enum class个条目的数组),并且有一个特殊的array literal syntax for annotations.列表和其他集合不能在批注中使用.

  • 至于用法,好的做法是在除代码的性能关键部分以外的任何地方都更喜欢使用列表而不是数组,理由与that for Java相同.

Kotlin相关问答推荐

Kotlin编译器如何决定是否可以在任何给定点调用Suspend方法?

处理合成层次 struct 中的深层按钮以切换视图

jOOQ Kotlin Coroutines - Select all and exists查询

用Quarkus和Reactor重写异步过滤器中的数据流

如何在 Spring Boot 3 中为内部类提供运行时提示

如何处理基于枚举提前返回的 forEach 循环,Kotlin 中的一条路径除外

Jetpack Compose:当状态从另一个活动改变时强制重组

使用 Compose for Desktop Bundle 文件

为什么我们在 kotlin 中需要 noinline?

是否可以在 kotlin 中嵌套数据类?

`DataBindingUtil` 中的 `bind`、`inflate` 和 `setContentView` 有什么区别

Foo::class.java 和 Foo::javaClass 有什么区别?

如何解决此错误请Kotlin:[Internal Error] java.lang.ExceptionInInitializerError

将协同路由调用放在存储库或ViewModel中哪个更好?

Kotlin not nullable值可以为null吗?

kotlin中的全局可拓函数

lateinit 的 isInitialized 属性在伴随对象中不起作用

如何在 Gradle Kotlin DSL 中使用来自 gradle.properties 的插件版本?

你如何在 Kotlin 中注释 Pair 参数?

目前不支持 Gradle 项目的自动库版本更新.请手动更新您的 build.gradle