If B2 may have many elements, then it may be best to sort B2, and then iterate over B1, using binary search to find an element in B2 that is equal to the current element in B1. If such an element is found, remove the current element in B1.
On the other hand, if B1 may have many elements but B2 has only a few elements, then you could do the above, but sort B1 instead and iterate over B2.
If both B1 and B2 will have only a few elements, then you could iterate over B2 and use B1's remove() method that takes an Object with the current element in B2. [ May 09, 2008: Message edited by: Eugene Wee ]
You might want to give a try to java.util.List's method removeAll(). Don't know how this method is implermented in ArrayList, so maybe one of the above approaches is faster, but using the JCF's on-board methods is usually a good idea.
The java.util.ArrayList is derived from java.util.AbstractList which again is derived from java.util.AbstractCollection. Now in the AbstractCollection class there are two functions namely, removeAllInternal(Collection c) and retainAllInternal(Collection c) but both of them are declared private so ArrayList cannot publicly override them.
You should be better off calling remove(Object obj) with each element in the collection containing objects to be removed. This method removes the first instance of obj so if you want to remove all occurrences you will have to take care of that. If the object has been found and removed successfully it returns a true otherwise a false is returned.
Originally posted by fundupuneet vyas: @ so how can i remove tht error for accomplishing the goal
Remove using the iterator; call l1.remove() instead of A1.remove(o);
And that basically removes the need for your code altogether and just replace it with A1.removeAll(B1), since this is the code of Java 6's implementation of AbstractCollection.removeAll (which is inherited by ArrayList):