Compare a Dynamic ArrayList with ArrayList! and remove the elements which are not present in Dynamic array

亡梦爱人 提交于 2019-12-23 02:52:50

问题


I have two ArrayLists, contactModels and list.

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));
       }

  }

But I can't achieve it.


回答1:


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.

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.

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);
       }
  }



回答2:


@Praneeth : There is API provided by Java. So you can use it. "list.removeAll(contactModels);"

if contactModel is having non primitive element then you can override equals and hash code to tell on what basis your object will be equal.

Now your list will contain only the unique element which is not there in contact models.

So now you don't need to have other method to remove it also.



来源:https://stackoverflow.com/questions/31378088/compare-a-dynamic-arraylist-with-arraylist-and-remove-the-elements-which-are-no

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!