Collection Framework

Collections framework was not a part of original Java release. Collections was added to J2SE 1.2. Prior to Java 2, Java provided adhoc classes such as Dictionary, Vector, Stack and Properties to store and manipulate groups of objects.

Framework in java means hierarchy of classes and interfaces.Collections framework is contained in java.util package. It provides many important classes and interfaces to collect and organize group of alike objects.


Important Interfaces of Collection API

InterfaceDescription
CollectionEnables you to work with groups of object; it is at the top of Collection hierarchy
DequeExtends Queue to handle double ended queue.
ListExtends Collection to handle sequences list of object.
QueueExtends Collection to handle special kind of list in which element are removed only from the head.
SetExtends Collection to handle sets, which must contain unique element.
SortedSetExtends Set to handle sorted set.

Collection Heirarchy

Collection Heirarchy

All these Interfaces give several methods which are defined by collections classes which implement these interfaces.


Why Collections were made Generic ?

Generics added type safety to Collection framework. Earlier collections stored Object class references which meant any collection could store any type of object. Hence there were chances of storing incompatible types in a collection, which could result in run time mismatch. Hence Generics was introduced through which you can explicitly state the type of object being stored.


Collections and Autoboxing

We have studied that Autoboxing converts primitive types into Wrapper class Objects. As collections doesn't store primitive data types(stores only refrences), hence Autoboxing facilitates the storing of primitive data types in collection by boxing it into its wrapper type.


Most Commonly thrown Exceptions in Collections Framework

Exception NameDescription
UnSupportedOperationExceptionoccurs if a Collection cannot be modified
ClassCastExceptionoccurs when one object is incompatible with another
NullPointerExceptionoccurs when you try to store null object in Collection
IllegalArgumentExceptionthrown if an invalid argument is used
IllegalStateExceptionthrown if you try to add an element to an already full Collection