Wednesday, May 22nd

Last update12:59:40 PM GMT


Write e-mail
Java CollectionsImagine, if you had to write data structure every time for storing the data in your object oriented application? And now you want to sort them, or want any operation like addition or deletion? It isn’t that difficult for programmers, but they can’t be expected to write the same code every time.

Java Collection framework serves the purpose, with the inbuilt methods and API to handle operations like sorting. Java Collections, in the form of interfaces and classes, are used to store different objects together and manipulate or process them. They are better than arrays, since they are dynamic in nature.


The basic features offered by collections are:
  • Adding an element
  • Removing an element
  • Finding, if an object exists in a collection
  • Retrieve an object from a collection
  • Iterate through a collection, using either an Iterator or enhanced for-loop, looking each object one after another.
And the basic methods for these operations, provided by Collection interface are:
  • int size()
  • boolean isEmpty()
  • boolean contains(Object element)
  • boolean add(Object element)
  • boolean remove(Object element)
The broad categories of Collection are:
  • Set – It is used to hold unique objects.
  • List – It is used to hold objects (two or more objects can be same).
  • Map – It is used to store (key, value) pair, where key need to be unique.

Set nameSet = new HashSet();


Variations and meaning of different collection word in Java:

  • collection (lowercase c), which represents any of the data structures in which objects are stored and iterated over.
  • Collection (capital C), which is actually the java.util.Collection interface from which Set, List, and Queue extend. (That's right, extend, not implement. There are no direct implementations of Collection.)
  • Collections (capital C and ends with s) are the java.util.Collections class that holds a pile of static utility methods for use with collections.
Prior to Java 5, there was no way to restrict the collection of holding a specific type of object. And hence, Generics were introduced in Java 5 which allows user to specify the object type for a collection. Like,
Set nameSet = new HashSet();

For sorting, the method used is Collections.sort(list). It works fine for predefined wrapper classes and String class. But for each user defined classes, the class need to implement Comparator or Comparable interface. For predefined wrapper classes in java and String class, the job is already done by Java. Thanks to Sun, I mean Oracle now!!

Share this post

Add comment

Please refrain from using slang or abusive language in the comments.
To avoid waiting for your comment to be published after being reviewed, please log in as a registered user.

Security code

Web Hosting