定義/初期値
Listには変更不可の「List」と可能な「MutableList」の2種類存在する。
1 2 3 4 5 6 7 8 9 10 11 |
val list: List<Int> list = listOf(1, 2, 3) list.forEachIndexed { index, element -> Log.d("MainActivity","list["+index+"]="+element) } val mutableList: MutableList<Int> mutableList = mutableListOf(1, 2 ,3) mutableList.forEachIndexed { index, element -> Log.d("MainActivity","mutableList["+index+"]="+element) } |
1 2 3 4 5 6 |
D/MainActivity: list[0]=1 D/MainActivity: list[1]=2 D/MainActivity: list[2]=3 D/MainActivity: mutableList[0]=1 D/MainActivity: mutableList[1]=2 D/MainActivity: mutableList[2]=3 |
追加、変更
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
val list: List<Int> list = listOf(1, 2, 3) //list.add(3) //エラー //list.set(0,9) //エラー list.forEachIndexed { index, element -> Log.d("MainActivity","list["+index+"]="+element) } val mutableList: MutableList<Int> mutableList = mutableListOf(1, 2 ,3) mutableList.add(4) mutableList.set(0,9) mutableList.forEachIndexed { index, element -> Log.d("MainActivity","mutableList["+index+"]="+element) } |
1 2 3 4 5 6 7 |
D/MainActivity: list[0]=1 D/MainActivity: list[1]=2 D/MainActivity: list[2]=3 D/MainActivity: mutableList[0]=9 D/MainActivity: mutableList[1]=2 D/MainActivity: mutableList[2]=3 D/MainActivity: mutableList[3]=4 |
アクセス
1 2 3 |
val mutableList: MutableList<Int> mutableList = mutableListOf(1, 2 ,3) Log.d("MainActivity","2番目"+mutableList.get(1)+":"+mutableList[1]) |
1 |
D/MainActivity: 2番目2:2 |
二次元配列
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
var list: MutableList<MutableList<String>> = mutableListOf() var list1 = mutableListOf("abc", "def", "ghi") var list2 = mutableListOf("jkl", "opq", "rstu") var list3 = mutableListOf("vwx", "yz!", "!#$") list.add(list1) list.add(list2) list.add(list3) list.forEachIndexed { index, element -> element.forEachIndexed { index2, element2 -> Log.d("MainActivity","list["+index+"]["+index2+"]="+element2) } } |
1 2 3 4 5 6 7 8 9 |
D/MainActivity: list[0][0]=abc D/MainActivity: list[0][1]=def D/MainActivity: list[0][2]=ghi D/MainActivity: list[1][0]=jkl D/MainActivity: list[1][1]=opq D/MainActivity: list[1][2]=rstu D/MainActivity: list[2][0]=vwx D/MainActivity: list[2][1]=yz! D/MainActivity: list[2][2]=!#$ |