Manoj
05/05/2021, 11:55 AMArrayList<String> arr = new ArrayList<>();
arr.add("1");
arr.add("2");
arr.add("3");
arr.add("4");
arr.add("5");
for (int i = 0; i < arr.size(); i++) {
if(i == 3) {
arr.remove(i);
} else {
System.out.println(arr.get(i) + "\n");
}
}
& I have converted the same code in Kotlin -
val arr = ArrayList<String>();
arr.add("1")
arr.add("2")
arr.add("3")
arr.add("4")
arr.add("5")
for (i in 0 until arr.size) {
if(i == 3) {
arr.removeAt(i)
} else {
println("Value ${arr.get(i)}")
}
}
bt it gives Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 4, Size: 4 but works in Java without exception... Anyone has any idea what's wrong here?iamthevoid
05/05/2021, 11:58 AMManoj
05/05/2021, 12:00 PMiamthevoid
05/05/2021, 12:09 PMval mutableListOf = mutableListOf(1,2,3,4,5)
mutableListOf.forEachIndexed { index, i ->
if (index == 3) mutableListOf.removeAt(index) else println(i)
}
iamthevoid
05/05/2021, 12:09 PMRoukanken
05/05/2021, 12:11 PMremoveAt(i)
in cycle?
In both Java and Kotlin you can call it outside of the cycle (since you pass it the index that you want to be removed...)
val arr = ArrayList<String>();
arr.add("1")
arr.add("2")
arr.add("3")
arr.add("4")
arr.add("5")
arr.removeAt(3)
for (i in 0 until arr.size) {
println("Value ${arr.get(i)}")
}
also, various other things in this code:
use mutableListOf("1", "2", ...)
instead that many arr.add
you can use arr[i]
instead of arr.get(i)
in kotlin, OR replace the whole for cycle via forEach
all in all your code can look like this:
val arr = mutableListOf("1", "2", "3", "4", "5")
arr.removeAt(3)
arr.forEach { println("Value $it") }
or
listOf("1", "2", "3", "4", "5")
.filterIndexed { index, _ -> index != 3 }
.forEach { it -> println("Value $it") }
Manoj
05/05/2021, 12:11 PMManoj
05/05/2021, 12:14 PMiamthevoid
05/05/2021, 12:14 PMiamthevoid
05/05/2021, 12:14 PMRoukanken
05/05/2021, 12:15 PMManoj
05/05/2021, 12:15 PMManoj
05/05/2021, 12:16 PMRoukanken
05/05/2021, 12:16 PMfilter
variants - give it your condition, and it will construct a new array of only elements that match that condition