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 '.
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.
Lists are like sets. They store a group of elements. But, lists will allow duplicate values to store in it.
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.
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:
List:
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:
- Using for-each loop
- Using Iterator interface
- Using ListIterator interface
- 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.