-
Java
- 可变:
ArrayList、HashMap等(默认集合大多可变)。 - 不可变:通过
Collections.unmodifiableList()包装,或 Guava 库的ImmutableList、ImmutableMap。
- 可变:
-
Kotlin
- 可变:
MutableList、MutableMap(带Mutable前缀的集合)。 - 不可变:
List、Map(默认声明的集合是不可变的,需显式用mutableListOf()创建可变集合)。
- 可变:
-
Python
- 可变:
list、dict、set(可直接增删改元素)。 - 不可变:
tuple(不能修改元素)、frozenset(不可变集合)。
- 可变:
-
C#
- 可变:
List<T>、Dictionary<TKey, TValue>(默认集合可变)。 - 不可变:通过
System.Collections.Immutable库的ImmutableList<T>、ImmutableDictionary<TKey, TValue>。
- 可变:
-
Swift
- 可变:用
var声明的数组 / 字典(var arr = [1,2,3])。 - 不可变:用
let声明的数组 / 字典(let arr = [1,2,3],无法修改元素)。
- 可变:用
package list
/*
* list: 有序,链表
*
* 可变与不可变
*/
object Base75 {
def main(args: Array[String]): Unit = {
// 可变的
val list1 = scala.collection.mutable.ListBuffer(1,2,3)
list1 += 4
println(list1)
// 不可变 不能直接修改原来的数据,
val list2 = scala.collection.immutable.List(1,2,3)
// list2 += 4 += 会报错
}
}
输出结果