Now i want modify List A1 such that, it will contain only element which are not present in List B1.
How can I do this?
Eugene Wee
Greenhorn
Joined: Dec 17, 2007
Posts: 5
posted
0
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 ]
Purushoth Thambu
Ranch Hand
Joined: May 24, 2003
Posts: 425
posted
0
Check "removeAll(Collection<?> c)" method in collections framework.
Guido Sautter
Ranch Hand
Joined: Dec 22, 2004
Posts: 142
posted
0
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.
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.
Hope this is what you were looking for?
Cheers, Raj.
Puneet N Vyas
Ranch Hand
Joined: Sep 20, 2007
Posts: 61
posted
0
@ just iterate over both array list and test if both the list has same element,then call remove method on that index..
Manuel Leiria
Ranch Hand
Joined: Jul 13, 2007
Posts: 171
posted
0
Results:
1 9
Have Fun!
Manuel Leiria<br /> <br />--------------<br />Peace cannot be kept by force; it can only be achieved by understanding. <br /> Albert Einstein
Puneet N Vyas
Ranch Hand
Joined: Sep 20, 2007
Posts: 61
posted
0
this is the code i wrote but it throws run time exception,can any one tell why?
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):