比较动态 ArrayList 和 ArrayList!并删除动态数组中不存在的元素 [英] Compare a Dynamic ArrayList with ArrayList! and remove the elements which are not present in Dynamic array

查看:22
本文介绍了比较动态 ArrayList 和 ArrayList!并删除动态数组中不存在的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个 ArrayListscontactModelslist.

contactModels 是一个动态数组列表,我需要比较这两个列表并删除 list 中的元素,而这些元素在 contactModels 中不存在>(DynamicArrayList).

The contactModels is a Dynamic Arraylist, I need to compare the two list and remove the elements in list, which are not present in contactModels(DynamicArrayList).

我尝试了嵌套循环,这是:

I tried nested loops, and this:

  for (int i = 0; i < list.size(); i++)
  {    
    if(!contactModels.get(i).getEmpID().equals(list.get(i).getEmpID()))
       {
        databaseadapter.removeContact(contactModels.get(i));
       }

  }

但我做不到.

推荐答案

您不是在测试 contactModels 中的项目是否不存在于 list 中.相反,您正在测试 contactModels 中索引处的项目是否与 list 中相同索引处的项目具有相同的 id.

you are not testing whether an item in contactModels is not present in list. instead you are testing whether the item at an index present in contactModels not has the same id as the item at the same index in list.

这仅在两个集合都根据 id 进行排序并且 contactModels 的条目至少与列表一样多时才有效.

this only works if both collections are sorted with respect to the id's and if contactModels has at least as much entries as list.

你是这种情况吗?否则这可能是您的问题.

is that the case for you ? otherwise this might be your problem.

如果您集合中的项目正确实现了 equalshashcode 并且如果它们的 id 相等,则它们相等,您可以使用类似这样的东西

if the items in your collections have equals and hashcode correctly implemented and are equal if their id's are equal you could use something like this

for (<TypeOfYourItems> item : list)
  {    
    if(!contactModels.contains(item))
       {
        databaseadapter.removeContact(item);
       }
  }

这篇关于比较动态 ArrayList 和 ArrayList!并删除动态数组中不存在的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆