Sunday 4 October 2015

Very very basics about collections in Java


What are Collections?
A collection - sometimes called a container - is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve, manipulate, and communicate aggregate data. Typically, they represent data items that form a natural group, such as a collection of strings, or a mapping of names to addresses.
How are collections (collection implementation classes) different from arrays?
Nope, they are not different. Array is nothing but a collection and our definition above proves that. Infact the collection implementation classes like ArrayList internally uses arrays to store objects. Vector, Hashtable and array are collection implementations in earlier versions (pre 1.2) of the Java Platform which unfortunately were not easy to extend, and did not implement a standard member interface. Well, they are not part of JDK collections framework but still they are collections.
Why do we need Collections Framework?
All three of these collections viz, Vector, Hashtable, array have different methods and syntax for accessing members: arrays use the square bracket ([]) symbols, Vector uses the elementAt method, and Hashtable uses get and put methods. These differences have forced programmers to implement their own inconsistent collections - some imitate the Vector access methods and some imitate the Enumeration interface. To make it worse, most of the Vector methods are marked as final; that is, you cannot extend the Vector class to implement a similar sort of collection. We could create a collection class that looked like a Vector and acted like a Vector, but it couldn't be passed to a method that takes a Vector as a parameter. Finally, none of the collections (array, Vector or Hashtable) implements a standard member access interface. When programmers develop algorithms (like sorting) to manipulate collections, what object should be passed to the algorithm - is it an array or a Vector or implement both interfaces? A lot of such questions pop up.
Thankfully, the Java Collections Framework (JCF) solves these problems and offers a number of advantages over using no framework or using the Vector and Hashtable

No comments:

Post a Comment