Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
279 views
in Technique[技术] by (71.8m points)

java - How to add an item to an arrayList in Kotlin only at specific positions?

I'm trying to add values to an arrayList only at specific positions. For example, if the value exists for position 0, then add it to array, else skip and get to next position and check the condition again. Is this possible? I tried something but I'm getting this error: java.lang.IndexOutOfBoundsException: Index: 1, Size: 0

My code:

for(item in reverseTicketsList){
        if(i<=6) {
            val value: String = item.total!!.replaceFirst(",", ".")
            val date: String = item.label!!.replace(".2020", "")
            var j = 0
            if (value.toFloat() != 0F) {
                if (item.values.first!!.toFloat() != 0F) {
                    hoursValuesArray.add(j, item.values.first!!.toFloat())
                    j++
                }

                else{
                   j++
                }
                if (item.values.second!!.toFloat() != 0F) {
                    hoursValuesArray.add(j, item.values.second!!.toFloat())
                    j++
                }
                else{
                    j++
                }
                if (item.values.third!!.toFloat() != 0F) {
                    hoursValuesArray.add(j, item.values.third!!.toFloat())
                    j++
                }
                else{
                   j++
                }
                entriesVerticalBar.add(BarEntry(i, hoursValuesArray.toFloatArray()))
                barLabesArrayList.add(date)
                i++
                hoursValuesArray.clear()
            }
        }

If you have any solutions please let me know! Thanks

EDIT A simpler example of what I'm trying to do and what I need:

val exampleArray: MutableList<Float> = ArrayList()
    exampleArray.add(0, 10f)
    exampleArray.add(2, 10f)
    exampleArray.add(4, 10f)
question from:https://stackoverflow.com/questions/65641206/how-to-add-an-item-to-an-arraylist-in-kotlin-only-at-specific-positions

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...