E
E
eegmak2021-07-09 15:39:20
Android
eegmak, 2021-07-09 15:39:20

Does the value of foreachindexed change in the loop after the element is removed?

I use a foreachindexed loop inside which I delete elements. The
question is: will the cycle go through the mutablelist elements according to the old value of the size of the structure, or will the cycle last one element less after deletion?

the code
fun removeFlower(num: Float) {
        val currentList = flowersLiveData.value
        val updatedList = initialFlowerList.toMutableList()
        updatedList.forEachIndexed{index, name ->
            Log.d(TAG, "найдем index="+index.toString());
            val q1=updatedList[index].lfreq.size/2-1
                for (fr in 0..q1)
                {
                    if (updatedList[index].lfreq[fr]<num && updatedList[index].lfreq[fr+1]>num)
                        break
                    else
                        if(fr==q1)
                            updatedList.removeAt(index)
                }

            }

        flowersLiveData.postValue(updatedList)

    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2021-07-09
@eegmak

forEachIndexed is an extension, sugar for for(x in list). And this is syntactic sugar for while(iterator.hasNext()). Next, you need to deal with the iterator, and there are options. The worst of them is ConcurrentModificationException, that is, changing the list that is currently being iterated over.
The answer is that you don't have to do it at all.
From the code, it looks like you just need to use iterator() directly and call remove() on it at the right time. And the index here is generally superfluous.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question