```public fun <T> MutableList<T>.remov...
# stdlib
d
Copy code
public fun <T> MutableList<T>.removeAll(predicate: (T) -> Boolean): Boolean = filterInPlace(predicate, true)

private fun <T> MutableList<T>.filterInPlace(predicate: (T) -> Boolean, predicateResultToRemove: Boolean): Boolean {
    if (this !is RandomAccess)
        return (this as MutableIterable<T>).filterInPlace(predicate, predicateResultToRemove)

    var writeIndex: Int = 0
    for (readIndex in 0..lastIndex) {
        val element = this[readIndex]
    ...
        if (writeIndex != readIndex)
            this[writeIndex] = element
     ...
}
It seems
CopyOnWriteArrayList.removeAll
does not copy on write but mutates in place instead
g
How so? Isn’t
CopyOnWriteArrayList::set
copying the array before mutation?
d
indeed
I am puzzled but a crash
Copy code
java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
        at java.util.concurrent.CopyOnWriteArrayList.get(CopyOnWriteArrayList.java:385)
        at java.util.concurrent.CopyOnWriteArrayList.get(CopyOnWriteArrayList.java:398)
        at kotlin.collections.CollectionsKt__MutableCollectionsKt.filterInPlace$CollectionsKt__MutableCollectionsKt(MutableCollections.kt:190)
        at kotlin.collections.CollectionsKt__MutableCollectionsKt.removeAll(MutableCollections.kt:177)
and
lastIndex
should be recalculated
s
Getting a similar crash while doing
removeAll
. I'm using SynchronizedList but I don't get why it's throwing IndexOutOfBounds.
Copy code
java.lang.IndexOutOfBoundsException: Index 0 out of bounds for length 0
	at jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
	at jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
	at jdk.internal.util.Preconditions.checkIndex(Preconditions.java:266)
	at java.util.Objects.checkIndex(Objects.java:385)
	at java.util.ArrayList.remove(ArrayList.java:558)
	at java.util.Collections$SynchronizedList.remove(Collections.java:2791)
	at kotlin.collections.CollectionsKt__MutableCollectionsKt.filterInPlace$CollectionsKt__MutableCollectionsKt(CollectionsKt__MutableCollectionsKt.java:296)
	at kotlin.collections.CollectionsKt__MutableCollectionsKt.removeAll(CollectionsKt__MutableCollectionsKt.java:270)