0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

KotlinでMutableListの操作

Posted at

はじめに

仕事でKotlinが必要になるのでを勉強している。
今回はリストの操作についてまとめる。

リストの操作

宣言

// 要素が空のリストを作成  
val emptyList = mutableListOf<String>()  
  
// 要素を指定して作成  
val list = mutableListOf("a", "b", "c")

mutableList は要素の追加、削除、変更ができるリスト。
一方、ノーマルな List は読み取り専用。

要素を取得する

val list = mutableListOf("a", "b", "c")

list.get(0) // => a  
list[1]    // => b

二通りの取得方法があるようだ。
使い分けは?好み?

要素を追加する

val list = mutableListOf("a", "b", "c")

list.add("d")  
println(list) // => [a, b, c, d]

イミュータブルな List では不可。

要素を変更する

イミュータブルな List では不可。

要素を指定して変更する

list[0] = "A"  
list.set(1, "B")  
println(list) // => [A, B, c, d]

全要素を同じ値で変更する

list.fill("x")  
println(list) // => [x, x, x]

全要素を変更する

val intList = mutableListOf(1, 2, 3, 4)  
intList.replaceAll { it * 2 }  
println(intList) // => [2, 4, 6, 8]

要素を削除する

list.removeAt(0)  
println(list) // => [B, c, d]

イミュータブルな List では不可。

おわりに

リストのネスト等、Javaと結構違うなと感じる部分も多いのでそれらはもう少し腹落ちしてからまとめたい。

0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?