Search This Blog

Thursday, December 3, 2009

According to the Java 6.0 above is the main Collection Interface hierarchy.



Collection Interface:


There is no direct implementation of root Collection interface (java.util.Collection).



Following Collection Interface methods.







The Collection interface is any group of objects, or elements with duplicates allowed. Use this interface to work with a group of elements in as general a s possilble.

public methods of Collection.



  • Adding and Removing:

boolean add(Object element)

boolean remove(Object element)



  • Query Operation:

int size()

boolean isEmpty()

boolean isEmpty()

boolean contains(Object element)

Iterator iterator()

Iterator interface return Iterator



  • Group Operations:

containsAll(Collection c) ---- checking subset

addAll(Collection c) ---- doing Union of two sets

clear() --- removing all elements

removeAll(Collection c) remove only subset

retainAll(Collection c) oppsite to removeAll method an intersection.


Object methods:

other are object methods.
Q: Who implements all these common methods??
A: AbstractCollection class.
Abstract Collection class provides implementations for all the methods expect for the iterator() and size() methods, which are implementted in the appropriate subclass. Optional methods like add() will throw an exception if the subclass doesn't override behavior.
Collection Framework Design concerns
In cretateion of the Collections Framework, the Sun development team needed to provide flexible interfaces that manipulated groups of elements. To keep the design simple, instead of provideing separate interfaces for optional capabilities, the interface define all the methods an implementation class may provide.
However, some of the interface methods are optional. because an interface implementation must provide implementations for all the interface methods, there need to be a way for calller to know if an optional method is not supported. The manner the framework development team chose to single callers when an optional method is called was to throw an UnsupportedOperationExcetpion. If in the course of using a colleciton an UnsupportedoperationException class is an extension of the RuntimeException class.
In addition to handling optional operatins with a run-time exception, the iterators for the concrete collection implementations are fail-fast. That means that if you are using an Iterator to traverse a collection while the underlying collection is being modified by another thread, then the Iterator fails immediately by throwing a ConcurrentModificationException (another runtime exception). That means the next time an iterator method is called, and the underlying collection has been modified the ConcurrentModificaitonException exception gets thrown.