List集合中的数据删除操作以及移除适配器中选中的项的问题

在for循环中操作list 并移除list中的项 如果for循环正序 当删除的时候 list的坐标会产生变化 会导致越界的问题

我们可以倒叙删除
for(int i=list.size();i>=0;i–){}
或者用迭代器
Iterator it=list.iterator();
  while (it.hasNext()){
it.remove();
}

下面来说一下 我昨天遇到的问题
列举手机里的apk文件 并选择删除
当时的操作是 双for循环 找到对应标记

  for(int i=0;i<listcheck.size();i++){
        for(int j=0;j<listgroup.size();j++){
                if(listcheck.get(i).name.equas(listgroup.get(j).name)){
                        listgroup.Remove(j);
}
}   
}

这个操作在子线程里 在主线程里同时也对这个集合listgroup集合进行了操作 结果下标越界了 涉及到了线程安全 这里就说点解决方案
为啥会这样
我在主线程和子线程同时访问了listgroup 造成的访问异常 有可能我在子线程中的操作结束 后刚好被主线程用到我操作完成的数据 就会造成各种问题 越界 空指针等
所以 应该用不同的list做对应处理
后面我将集合操作放到主线程让主线程去操作就解决了问题下面贴一下代码
/**
* 移除apk选中的apk文件
*/
public void RemoveApk() {
Analytics.getInstance(PhotoClearApplication.getApplication().getApplicationContext())._sendEvent("安装包管理", "清理开始");
Firebase.getInstance(PhotoClearApplication.getApplication()).logEvent("安装包管理", "清理开始");
new Thread(new Runnable() {
@Override
public void run() {
List<MyFile> fileList = apkAdapter.getList();
for (int i = 0; i < fileList.size(); i++) {
for (int j = list_myfile.size() - 1; j >= 0; j--) {
if (fileList.get(i).getName().equals(list_myfile.get(j).getName())) {
list_myfile.get(j).ischeck = fileList.get(i).ischeck;
}
}
}
Iterator it = list_myfile.iterator();
while (it.hasNext()) {
MyFile files = (MyFile) it.next();
if (files.ischeck) {
File file = new File(files.getFilePath());
file.delete();
// it.remove();// 子线程中remove 两个线程同时操作的一个list集合 就会出现越界的问题将集合操作放到主线程里
}
}
handler.sendEmptyMessage(REMOVE);
}

    }).start();
}


Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case REMOVE:
//将对集合的操作放到主线程来
Iterator it = list_myfile.iterator();
while (it.hasNext()) {
MyFile files = (MyFile) it.next();
if (files.ischeck) {
it.remove();
}
}
apkAdapter.notifyDataSetChanged();
setHeaderShow(list_myfile, tvShowAs);
list_myfile = apkAdapter.getData();
btRemove.setBackgroundColor(getResources().getColor(R.color.removeButton));
btRemove.setText(R.string.remove_apk_default);
Analytics.getInstance(PhotoClearApplication.getApplication().getApplicationContext())._sendEvent(“安装包管理”, “清理结束”);
Firebase.getInstance(PhotoClearApplication.getApplication()).logEvent(“安装包管理”, “清理结束”);
break;`

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值