You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何初始化固定大小的ArrayList?传入count=4却长度为0的问题

如何初始化固定大小的集合/数组并正常遍历

你遇到的问题核心是:ArrayList<ImageView>(count)这个写法只是设置了ArrayList的初始容量,并不是直接创建包含count个元素的集合——此时集合内部还是空的,所以forEachIndexed自然不会执行。

下面是几种可行的解决方法:

方法1:先填充元素再遍历

先通过循环创建count个ImageView实例并添加到集合中,之后就能正常遍历:

private fun setupIndicators(count: Int) {
    val indicators = ArrayList<ImageView>(count)
    // 循环创建并添加count个ImageView
    repeat(count) {
        val imageView = ImageView(context) // 需传入实际上下文,根据场景调整
        // 可在此设置ImageView的默认属性(比如大小、占位图等)
        indicators.add(imageView)
    }

    // 现在集合有元素,forEachIndexed可正常执行
    indicators.forEachIndexed { index, element ->
        // 编写你的业务逻辑
    }
}

方法2:直接遍历次数,同步添加元素

如果不需要先把所有元素都存入集合再遍历,可以直接用repeat循环指定次数,一边创建元素一边处理逻辑:

private fun setupIndicators(count: Int) {
    val indicators = ArrayList<ImageView>(count)
    
    repeat(count) { index ->
        val imageView = ImageView(context)
        // 直接处理当前index对应的ImageView逻辑
        indicators.add(imageView)
    }
}

方法3:创建固定大小的数组(非ArrayList)

如果需要的是真正固定大小的数组,而非可变集合,可以使用Array类直接初始化:

private fun setupIndicators(count: Int) {
    // 创建固定大小的数组,每个位置直接初始化ImageView
    val indicators = Array(count) { ImageView(context) }
    
    // 遍历数组
    indicators.forEachIndexed { index, element ->
        // 编写你的业务逻辑
    }

    // 若需要转成ArrayList,可调用toMutableList()
    val arrayList = indicators.toMutableList()
}

补充说明:ArrayList的构造参数count是初始容量,作用是提前分配足够的内存空间,避免后续添加元素时频繁扩容,但不会自动填充元素——集合的实际元素数量还是0,必须手动添加元素后才有内容。

内容的提问来源于stack exchange,提问作者Captai-N

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 15:46:17