Kotlin数组或集合遍历之删除大坑

Kotlin数组或集合遍历之删除大坑

        例如一下情况:

fun removeDevice(bleDevice: BleDevice) {
         for (i in bleDeviceList.indices) {
            val device = bleDeviceList[i]
            if (bleDevice.key == device.key) {
                bleDeviceList.removeAt(i)
             }
        }
    }
使用以上方法来遍历集合来删除重复元素,你会发现它能报边界溢出
假设 bleDeviceList.size = 6  bleDeviceList.indices起始为0..5 ,i起始为0
原因:每次遍历i都会加1,开始之后bleDeviceList.indices固定不变
所以当你删除一个元素之后,后面的元素会前移,
新bleDeviceList.indices减1了。
而寻找下标加1,所以有可能 i>新的bleDeviceList.size
以上过程为:
1:i=0 i<6  bleDeviceList.size =6  device = bleDeviceList[0] 
假设重复 删除 则bleDeviceList后面元素前移 则新bleDeviceList.size =5

2:i=1 i<6  bleDeviceList.size =5  device = bleDeviceList[1]
假设重复 删除 则bleDeviceList后面元素前移 则新bleDeviceList.size =4

3:i=2 i<6  bleDeviceList.size =4  device = bleDeviceList[2]
假设重复 删除 则bleDeviceList后面元素前移 则新bleDeviceList.size =3

4:i=3 i<6  bleDeviceList.size =3  device = bleDeviceList[3]
因为bleDeviceList.size =3 所以可取下标为 0,1,2 所以当取bleDeviceList[3]时边界溢出

tips:试了迭代器也不行
解决办法(简单粗暴)

fun removeDevice(bleDevice: BleDevice) {
        var y :Int?=0
        for (i in bleDeviceList.indices) {
            val device = bleDeviceList[i-y!!]
            if (bleDevice.key == device.key) {
                bleDeviceList.removeAt(i-y)
                y++
            }
        }
    }
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值