Tuesday, 30 April 2013

Collection in Java

What is Collection?

Collection if we go by name means group of some entities. From a bit more technical perspective it means an object that groups multiple elements into single unit.Collections are used to store, retrieve, manipulate and communicate aggregate data.

Collection framework in Java

A collection framework is a unified architecture for representing and manipulating collections.All collection frameworks contain the following -

All of the collection framework is represented by the following picture -

Each of the above will be taken individually and explained but lets take one example to understand Collection frameworks.

First thing to note is that Collectioninterface is the top most entity in the entire Collection tree.Yes it is an interface and all other entities in Collection(List,Set,Queue) implement this Collection interface.Collection interface also implements an interface called Iterable which allows us to iterate over the elements stored in the collection but do not worry about it for now.We will explain it separately.
If you see above picture List is a Collection.Note again that List is still an interface and multiple implementations of it are possible. Example we can have ArrayList, LinkedList, Stack, Vector etc. Each concrete implementations just mentioned will have different Algorithms associated with them.

Note : Map interface and it's concrete implementations do not form a part of Collections i.e Map interface does not implement Collection yet it is a part of Java Collection framework. Also since Map interface does not extend Collection interface(which in turn implements Iterable interface) Map cannot be directly iterated over it's elements. There is another way of-course but we shall see it later.