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++
}
}
}