Welcome Message

Hi, welcome to my website. This is a place where you can get all the questions, puzzles, algorithms asked in interviews and their solutions. Feel free to contact me if you have any queries / suggestions and please leave your valuable comments.. Thanks for visiting -Pragya.

June 22, 2010

Details of retainAll() in Set interface

The Set interface contains a method 'retainAll()' which gives us the intersection of two sets.

Lets say we define a Set as : Set s = new HashSet();

HashSet class extends the abstract class AbstractSet , which in turn extends the abstract class AbstractCollection. The implementation of retainAll() is present in AbstractCollecction class.

This method Retains only the elements in this collection that are contained in the
specified collection (optional operation). In other words, removes
from this collection all of its elements that are not contained in the
specified collection.



This implementation iterates over this collection, checking each
element returned by the iterator in turn to see if it's contained
in the specified collection. If it's not so contained, it's removed
from this collection with the iterator's remove method.



Note that this implementation will throw an
UnsupportedOperationException if the iterator returned by the
iterator method does not implement the remove method
and this collection contains one or more elements not present in the
specified collection.

No comments: