java - IndexOutOfBoundsException for for-loop in Kotlin -
i have 2 list in kotlin, of same size, foodobjects: mutablelist<parseobject>?
, checked: mutablelist<boolean>?
. need cycle , objectid foodobjects
every time element of checked
true. in java:
for(int = 0; i< foodobjects.size(); i++) { //here }
but in kotlin, don't know why, there problems. in fact, if this:
for(i in 0..foodobjects!!.size) { if (checked?.get(i) == true) { objectsid?.add(foodobjects.get(i).objectid) } }
i've got indexoutofboundsexception
: don't know why, continue cycle @ foodobjects.size
. filter , map:
(0..foodobjects!!.size) .filter { checked?.get(it) == true } .foreach { objectsid?.add(foodobjects.get(it).objectid) }
but i'm giving same error. need stop using if:
for(i in 0..foodobjects!!.size) { if(i < foodobjects.size) { if (checked?.get(i) == true) { objectsid?.add(foodobjects.get(i).objectid) } } }
to works.
everyone tell me why in kotlin need it, when in java works good?
ranges in kotlin inclusive, therefore 0..foodobjects!!.size
starts @ 0
, ends @ foodobjects.size
, including both ends. causes exception when loop attempts index list own size, 1 more largest valid index.
to create range doesn't include upper bound (like java loop), can use until
:
for(i in 0 until foodobjects!!.size) { // ... }
you clean code bit if did null checks on collections you're using front:
if (foodobjects != null && checked != null && objectsid != null) { (i in 0 until foodobjects.size) { if (checked.get(i) == true) { objectsid.add(foodobjects.get(i).objectid) } } } else { // handle case when 1 of lists null }
and rid of having handle indexes altogether, can use indices
property of list (plus use indexing operator here instead of get
calls):
for (i in foodobjects.indices) { if (checked[i]) { objectsid.add(foodobjects[i].objectid) } }
you use foreachindexed
:
foodobjects.foreachindexed { i, foodobject -> if (checked[i]) { objectsid.add(foodobject.objectid) } }
Comments
Post a Comment