Android/kotlin/配列
提供: 初心者エンジニアの簡易メモ
目次
配列
自分はforeachはbreakなどが使えないので、for-inのほうが好き
for-in
var names:ArrayList<String> = arrayListOf("taro", "jiro") if (names.isNotEmpty()) { for (name: String in names) { Log.d("test", "name=" + name) } }
or
foreach
names:Array.forEach { Log.d("test", "name=" + it) }
配列プロパティ値取得
User.kt
class User { var name: String = "" }
var user = User() user.name = "taro" var user2 = User() user2.name = "jiro" var users: ArrayList<User> = arrayListOf(user, user2) var username = users.firstOrNull { it.name.contains("taro") }?.name ?: "" // taro for (user: User in users) { Log.i("test", "user.name=" + user.name) }
配列プロパティ条件一致で更新
var user = User() user.name = "taro" var user2 = User() user2.name = "jiro" var users: ArrayList<User> = arrayListOf(user, user2) users.firstOrNull {it.name == "taro"}?.name = "saburo" // taroをsaburoへ for (user: User in users) { Log.i("test", "user.name=" + user.name) }
mutableリストに文字列追加
val names = mutableListOf<String>() for (i in 1..10000) names.add("name" + i)
配列をnullでいれて、空の配列用意
private var names: ArrayList<string?>? = null names = ArrayList() names!!.add("taro") // データ挿入