可变与不可变

46 阅读1分钟
  1. Java

    • 可变:ArrayListHashMap等(默认集合大多可变)。
    • 不可变:通过Collections.unmodifiableList()包装,或 Guava 库的ImmutableListImmutableMap
  2. Kotlin

    • 可变:MutableListMutableMap(带Mutable前缀的集合)。
    • 不可变:ListMap(默认声明的集合是不可变的,需显式用mutableListOf()创建可变集合)。
  3. Python

    • 可变:listdictset(可直接增删改元素)。
    • 不可变:tuple(不能修改元素)、frozenset(不可变集合)。
  4. C#

    • 可变:List<T>Dictionary<TKey, TValue>(默认集合可变)。
    • 不可变:通过System.Collections.Immutable库的ImmutableList<T>ImmutableDictionary<TKey, TValue>
  5. 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  += 会报错
  }
}

输出结果

image.png