I have some code in Java like this - ```ArrayList&...
# android
m
I have some code in Java like this -
Copy code
ArrayList<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 -
Copy code
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?
i
looks like arr.size() in java requests every iteration, but in kotlin only single time
m
so what's the Kotlin equivalent for this Jaava code?
i
something like that
Copy code
val mutableListOf = mutableListOf(1,2,3,4,5)

mutableListOf.forEachIndexed { index, i ->
    if (index == 3) mutableListOf.removeAt(index) else println(i)
}
But better you shouldn’t do like that )
r
why are you doing
removeAt(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...)
Copy code
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:
Copy code
val arr = mutableListOf("1", "2", "3", "4", "5")
arr.removeAt(3)
arr.forEach { println("Value $it") }
or
Copy code
listOf("1", "2", "3", "4", "5")
    .filterIndexed { index, _ -> index != 3 }
    .forEach { it -> println("Value $it") }
👍 1
m
Thanks @iamthevoid.... will check this... basically I am converting my existing Java project to Kotlin... but stuck with this issue
Thanks @Roukanken... this is just a pseudo code. And in actual project I have that item removed within the loop based on some conditions
i
I am agreed with @Roukanken. Deleting items in cycle leads implicit bugs
Or just code becomes hard to understand
r
I still recommend not iterating over collection while deleting stuff out of it
m
👍 Agree
will change that code
r
either use two for cycles - delete AND iterate after that, or much better solution is use one of many
filter
variants - give it your condition, and it will construct a new array of only elements that match that condition
👍 1