0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

kotlin List Set Mapの特徴

Posted at

List Setの違い

List

  • 重複要素を許可
  • 要素の順番を保持
fun main() {
    val intList = listOf(1,1,2) // 重複要素も許可
    println(intList) //[1, 1, 2]
}

Set

  • 重複要素を持てない
  • 要素の順番を保証しない
fun main() {
    val intList = setOf(1,1,2) //重複は自動で削除
    println(intList) //[1, 2]
}

重複は自動で削除される

ミュータブルとイミュータブル

List, Set, Mapはイミュータブル(読み取り専用)になります。
ミュータブルな型を使用する場合は、MutableList,MutableSet,MutableMapを使用します。

使用方法

val intList = listOf(1, 2, 3)
val intSet = setOf(1, 2, 3)
val intMap = mapOf(1 to 10, 2 to 20, 3 to 30)

val intMutableList = mutableListOf(1, 2, 3)
val intMutableSet = mutableSetOf(1, 2, 3)
val intMutableMap = mutableMapOf(1 to 10, 2 to 20, 3 to 30)
//Mutableな型は要素の追加が可能
intMutableList.add(4) //[1, 2, 3, 4]
intMutableSet.add(4) //[1, 2, 3, 4]
intMutableMap[4] = 40 //{1=10, 2=20, 3=30, 4=40}

値を入れずに宣言だけする場合

val intMutableList: MutableList<Int> = mutableListOf()
val intMutableSet: MutableSet<Int> = mutableSetOf()
val intMutableMap: MutableMap<Int, Int> = mutableMapOf()
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?