Skip to main content

collection framework in java with example

Collection framework is a class library to handle group of objects. Collection framework implemented in java.util package. A collection object or container object is an object which can store a group of other objects. A collection object has a class called ' Collection class ' or ' Container class '. All the collections classes are available in the package java.util (util stands for utility). A group of collection classes are called a ' Collection Framework '.



The above diagram represents the hierarchy of Collection Framework and the list of available interfaces with their implementation classes.

How can we handle a group of elements?
We use an array to store a group of elements and handle them easily.

How can we handle a group of objects? How can we use an array to store a group of objects?
Yes, it is possible to use an array to store a group of objects.

Using an array to store a group of objects:
We can also store group of objects into an array. Let us take an example, where we want to store 100 Employee class objects into an array. To store these Employee objects into an array we have to an Employee type of Array.
Employee arr[] = new Employee[100];

The above Employee Type of Array will store max 100 Employee objects into it. If you have tried inserting more than 100 Employee objects, will throw ArrayIndexOutOfBound Exception. To store Employee objects into Employee type of array, I am using the for loop as like below,
for(int i=0;i<100;i++){
   arr[i] = new Employee();
}

Ex:   Here, is the program to store a group of objects into an array and retrieve the object data and display.
package com.javatbrains.collections;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

class Employee {
     int id;
     String name;

     Employee(int id, String name) {
          this.id = id;
          this.name = name;
     }

     // A method to display data
     void display() {
          System.out.println(id + "\t" + name);
     }
}

public class Group {

     public static void main(String[] args) throws NumberFormatException, IOException {
          //Accept data from keyborad
          BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
         
          //Create employee type array with size 5
          Employee arr[] = new Employee[5];
         
          //Store 5 employees data into array
          for (int i = 0; i < 5; i++) {
              System.out.println("Enter Id: ");
              int id = Integer.parseInt(br.readLine());
              System.out.println("Enter Name: ");
              String name = br.readLine();
              arr[i] = new Employee(id,name);
          }
          System.out.println("\n The employee data is: ");
          for(int i = 0;i<arr.length;i++){
              arr[i].display();
          }
     }

}

Now, we have an idea how to store a group of objects into an array and retrieve those objects from an array. There are some inconvenience in this mechanism. That are,
  • We can not store different type of objects into the same array. The reason is that an array can store only one data type of elements.
  • Adding the objects at the end of an array is easy. But, inserting and deleting the elements in the middle of the array is difficult. In this case, we have to rearrange all the elements of the array.
  • Retrieving the elements from an array is easy but retrieving the elements, if we want to process them, then there are no methods available to carry out this.
Due to this reasons, programmer wants better mechanism to store a group of objects into an array. The alternative is using an objects to store a group of other objects. It means that we can use a class object as an array. Such object called as 'collection object' or 'container object'.

These are also advantages of collection framework and disadvantages of using normal arrays.  All the collection classes in java.util package are the implementation classes of different interfaces.

Interface type
Implementation classes
Set<T>
HashSet<T>
TreeSet<T>
LinkedHashSet<T>
List<T>
Stack<T>
LinkedList<T>
ArrayList<T>
Vector<T>
Queue<T>
LinkedList<T>
Map<K,V>
HashMap<K,V>
HashTable<K,V>

Set:
           A Set represents a group of elements. The set will grow dynamically when elements storing into it. A set will not allow duplicate elements. If we try to pass the same element that is already available in the set, then it will not stored into the set.

List:
           Lists are like sets. They store a group of elements. But, lists will allow duplicate values to store in it.

Queue:
           A Queue represents arrangement of elements in FIFO (First In First Out) order. This means that the element which stored in first it will remove first from the queue.

Map:
          Map store elements in the form of key and value pairs. If key has provided the corresponding value we can get. Keys should have unique values.
         
Note: In all the cases elements refers to objects only. This means we can not store primitive data types in the collection objects.

Retrieving elements from Collections:
There are 4 ways to retrieve any element from a collection object:
  1. Using for-each loop
  2. Using Iterator interface
  3. Using ListIterator interface
  4. Using Enumeration interface
for-each loop:
for-each loop is like for loop which repeatedly executes a group of statements for each element of the collection.
for(variable : collection-object){
    statements;  
}

Here, the variable assumes each element of the collection-object and the loop executes as many times as there are number of elements in the collection-object.

Iterator interface:
Iterator is an interface that has the methods to retrieve the elements one by one from a collection object. It has 3 methods:
            •   boolean hasNext() :  This returns true if the iterator has more elements.
            •    element next() : This method returns the next element in the iterator..
            •   void remove() : This method removes from the collection the last element returned by the iterator.

ListIterator interface:
ListIterator is an interface that contains the methods to retrieve the elements from the collection object, both in forward and reverse direction.
            •    boolean hasNext(): this returns true if the ListIterator has more elements when traversing the list in the forward direction.
            •    boolean hasPrevious(): this returns true if the ListIterator has more elements when traversing the list in the reverse direction.
            •   element next(): this returns the next element in the list.
            •   element previous(): this returns the previous element in the list.
            •    void remove(): this removes from the list the last element that was returned by the next() or previous() methods.

Enumeration Interface:
This interface is useful to retrieve one by one the elements like the iterator. It has 2 methods,
            •   boolean hasMoreElements(): this method tests if the Enumerator has any more elements.
            •   element nextElement(): this returns the next element that is available in Enumeration.

Popular posts from this blog

Multithreading in java with example

Multithreading  is one of the most important concept in core java. In this article we will learn what is multithreading? , what is the use of it? and What is the use of Synchronization and when to use it?  with detailed examples. At a time, two or more threads are accessing the same object is called as Multithreading  in Java .  First, we will create two threads for two objects. It is also possible to run two or more threads on a single class object. In this case, there is a possibility to get unreliable results. If the two threads are perform same task, then they need same object to be executed each time. For your better understanding, take an example of any reservations like, railway, movie ticket booking,etc. Let us think only one berth is available in a train and two passengers are asking for that berth. The first person has sent a request to allocate that ticket/berth to him. At the same time, the second person also sent a request to allocate that ...

JNDI configuration for Tomcat 9 with Oracle

In this article, I am going to place the required source code to get data from the table by using the JNDI configuration. Below are the environment details that I have configured currently. Windows - 7 Oracle - 10g Tomcat - 9 JDK - 8 Eclipse Oxygen Ojdbc6 jar required First, we need to create the Dynamic Web Project. If you don't know how to do <Click Here>. I have faced a lot of issues before getting the output like 405, No driver class to load, etc. I am using JSP & Servlets in the current explanation. Before started writing the application logic, we need to do the below configuration in the installed tomcat directory. Place OJDBC6.jar in the Tomcat LIB directory. Add this Resource under <GlobalNamingResources> in Server.xml file which is present under the conf directory in Tomcat. < Resource name = "jdbc/myoracle" global= "jdbc/myoracle" auth = "Container" type= "javax.sql.DataSource" driverClass...

Git installation for AngularJS 2 in Windows 10

Download Git latest version from https://git-scm.com/downloads or you click on the below link to download directly for windows https://git-scm.com/download/win . Once download completes, click on executable file to start installation process and choose Yes to allow the software installation in windows 10. Click on Next button to continue further installation. Browse the isntallation directory and click on Next button to continue. Select the list of components which you want to be installed and click on Next button to proced further installation. Type the shortcut name for Start menu and click on Next button. Select how you want to use the Git and click on Next button. For Windows no need to change anything, let it be the default one. Choose the Use the OpenSSL library and click on Next button. Select how should Git treat line ending in text files and click on Next button. Select which terminal emulator to use with Git and click on Next button. Configure extr...