问题
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