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)
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>
有add
和remove
个函数,因此它可以增加和减少其大小.
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
数组针对原语进行了优化:有单独的IntArray
、DoubleArray
、CharArray
等映射到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相同.