^

The Collection Framework

Before starting discussion on collection framework, consider the following program to create a group of objects in memory using arrays:
class Employee
{
int ID;
String EName;
Employee(int ID,String EName)
{
this.ID=ID;
this.EName=EName;
}
public String toString()
{
return("ID="+ID+"Emp.Name ="+EName);
}
}
class demo
{
public static void main(String args[])
{
//creation of array of objects
Employee E[]=new Employee[3];
E[0]=new Employee(101,"Aman");
E[1]=new Employee(102,"Raman");
E[2]=new Employee(103,"Sandy");
System.out.println("Employee list");
for(int i=0;i<E.length;i++)
{
System.out.println(E[i]); //calling toString
}
}
}
                
    OUTPUT
		ID = 101 			Emp. Name: Aman
		ID = 102 			Emp. Name: Raman
		ID = 103 			Emp. Name: Sandy

There are some inconveniences with array of objects. They are as follows:
  1. Different class objects cannot be stored.
  2. Insertion and deletion of object is difficult because we have to write additional code for it.
  3. The size of array cannot be changed at run time
Due to the above written inconveniences, programmers want a better mechanism, which is possible using collection framework.

The Java Collection Framework

A collection allows a graoup of objects to be treated as a single unit. The Java collection framework provides a set of standard utility classes for managing various kinds of col-lections. The core framework is provided in the java.util package and it consists of three main parts:
  1. Interfaces:These generic interfaces define the common functionality
  2. Concrete Classes: These are specific implementations of core interfaces.
  3. Static Utility Methods: Collections and Array classes provide various methods to preform different op-erations on collections, such as sorting, searching etc.

TheCoreCollection Interfaces and Their Implementations

The java.util package provides the interfaces and their corresponding concrete imple-mentation classes. No concrete class directly implements the Collection interface. Re-member, all concrete classes implement Serializable and Cloneable interfaces, there-fore, the objects of all these classes can be serialized and cloned.
The following figure shows the core interfaces and their implementations.
The following figure shows core Map interfaces and their implementations:

Retrieving Elements From Collection

Following are the four ways to retrieve elements from collection:
  1. Using for-each Loop
  2. Using Iterator Interface
  3. Using ListIterator Interface
  4. Using Enumeration Interface
1. for-each Loop:
It is like a ‘for’ loop that executes a group of statements for each item in the collection.
2. Iterator Interface:
It is generic interface having the following three methods
  1. boolean hasNext(): returns true if the iterator has more elements.
  2. E next() : returns next elements in the collection.
  3. Void remove() : removes the element returned by next().
3. ListIterator Interface:
ListIterator is a bidirectional iterator for the lists. It extends the Iterator interface. It has the following methods: 4. Enumeration Interface:
It is also used to retrieve elements one by one from the list, like Iterator. It has two methods:
Difference Between Iterator and Enumeration
  1. Iterator is new and improved version, where method names are shorter and has a new method,remove()
  2. Enumerationacts as read-only interface because it has the methods only to traverse and fetch the objects whereas by using Iterator,we can manipulate the objects, like adding and removing them from the collection.
  3. Iteratoris more secure and safe as compared to Enumeration because it does not allow other threads to modify the objects while a thread is iterating over it and throws ConcurrentModificationException.

ArrayList<E>, LinkedList<E> & Vector<E> Classes

These are concrete classes that implement List interface. These classes are provided in java.util package.
Vector and ArrayList classes are implemented using dynamically resizable arrays, providing fast random access and fast list traversal. But unlike ArrayList class, the Vector class is thread-safe. Both classes offer comparable performance but Vector suf-fers a slight performance penalty due to synchronization. ArrayList implementation is overall best choice for programmers.
LinkedList implementation uses a doubly linked list. Insertion and deletion in doubly linked list are very efficient. In addition to the List interface, LinkedList class also im-plements the two other interfaces: Queue & Deque, that makes it to be used for stack and queue operations.

ArrayList Class

ArrayList class can be written as ArrayList. E represents the type of elements to be stored in ArrayList.
ArrayList class contains the following constructors:
  1. ArrayList ()
  2. ArrayList(Collection <? Extends E >C)
  3. ArrayList(int capacity )
The first constructor creates a new empty ArrayList with default capacity 10.
The second constructor creates a new ArrayList containing elements in the specified collection. The LinkedList class also provides constructor that are analogous to the two ArrayList constructors.
The third constructor creates new ArrayList with specified capacity
ArrayList class consists of the following methods:
import java.util.*;

class Product
{
  int pid;
  float price;
  String what;
  Product(int pid,float price,String what)
  {
	  this.pid=pid;
	  this.price=price;
	  this.what=what;
  }
  public String toString()
   {
	return (pid+"  "+what+ " "+price);  
   }
}
public class iterators 
 {
	static void useIterator(ArrayList store)
	 {
		Iterator itr=store.iterator();
		while(itr.hasNext())
		 {
			Product p=itr.next();
			System.out.println(p);
		 }
	}
	static void useListIterator(ArrayList store)
	 {
		ListIterator litr=store.listIterator();
		litr.next();
	while(litr.hasNext())
		 {
			Product p=litr.next();
			System.out.println(p);
		}
	//using hasPrevious() & previous()
	while(litr.hasPrevious())
	{
		Product p=litr.previous();
		System.out.println(p);
	}
	}
	static void useEnumeration(ArrayList store)
	 {
		Enumeration enm=Collections.enumeration(store);
		while(enm.hasMoreElements())
		 {
			Product p=enm.nextElement();
			System.out.println(p);
		}
	}
	static void useForEach(ArrayList store)
	{
		for(Product p:store)
		{
			System.out.println(p);
		}
	}
	
	public static void main(String[] args) 
		{
			ArrayList store=new ArrayList();
			store.add(new Product(101,50000,"Laptop"));
			store.add(new Product(102,800000,"Car"));
			store.add(new Product(103,35000,"Mobile"));
			store.add(new Product(104,30000,"Desktop"));
			
		iterators.useIterator(store);
		System.out.println("-------------------------------------");
		iterators.useForEach(store);
		System.out.println("-------------------------------------");
		iterators.useEnumeration(store);
		System.out.println("-------------------------------------");
			iterators.useListIterator(store);
		for (int i = 0; i < store.size(); i++)
		{
				Product p=store.get(i);
				System.out.println(p);
		}
		}

}

             
    Output
            101 Laptop 50000.0
            102 Car 800000.0
            103 Mobile 35000.0
            104 Desktop 30000.0
        ---------------------------------------
            101 Laptop 50000.0
            102 Car 800000.0
            103 Mobile 35000.0
            104 Desktop 30000.0
        ---------------------------------------
            101 Laptop 50000.0
            102 Car 800000.0
            103 Mobile 35000.0
            104 Desktop 30000.0
         ---------------------------------------
            102 Car 800000.0
            103 Mobile 35000.0
            104 Desktop 30000.0
            104 Desktop 30000.0
            103 Mobile 35000.0
            102 Car 80000.0
            101 Laptop 30000.0
         ---------------------------------------

             
The following program demonstrates some commonly used methods of ArrayList class:
import java.util.*;

  class ArrayListProgram {
       public void learnArrayList()
		   {
        int MAX = 10;
        int counter = 0;
        List<Object> listA = new ArrayList<Object>();
        List<Object> listB = new ArrayList<Object>();
        System.out.println("  - Storing 10 Integer Objects");
        for (int i = 0; i < MAX-1; i++) 
		{   
            listA.add(new Integer(i));
        }
         System.out.println(" Storing Strings");
        listA.add("Aman");
        listA.add("Raman");
        listA.add("Manjeet Singh");
        listA.add("Salman Khan");
        System.out.println("| Retrieve objects using an Iterator:");
         Iterator<Object> i = listA.iterator();
        while (i.hasNext()) 
        {  	Object ob=i.next();
            System.out.print(ob+" , ");
        }
    
        int loc = listA.indexOf("Raman");
        System.out.println("\nIndex location of the String Raman is: " + loc);  
        List<Object> listSub = listA.subList(10, listA.size());
        System.out.println("New Sub-List " + listSub);
         /*//Collections.sort(listSub);
        System.out.println("New Sorted List : " + listSub);
        System.out.println("Original List     : " + listSub);*/
        Collections.reverse(listSub);
        System.out.println("New Reversed List : " + listSub);
       System.out.println("Is Sub-List empty? " + listSub.isEmpty());
       System.out.println("Are List's A and B equal? " + listA.equals(listB));
       System.out.println("************List A   (Before)  : " + listA);
        Collections.shuffle(listA, new Random());
        System.out.println("************List A   (after)  : " + listA);
       System.out.println("Are List's A and B equal? " + listA.equals(listB));
        System.out.println("| Convert a List to an Array.|");
        Object[] objArray = listA.toArray();
       for (int j=0; j < objArray.length; j++) 
		{
            System.out.print(" , Element [" + j + "] = " + objArray[j]);
        }
        System.out.println("\n| Remove (clear) Elements from List A.  |");
        System.out.println("List A   (before) : " + listA);
       listA.clear();
        System.out.println("List A   (after)  : " + listA);
     }
    }
class Collection_ArrayList
  {
	 public static void main(String[] args)
	  {
		 ArrayListProgram listExample = new ArrayListProgram();
	        listExample.learnArrayList();
	  }
  }
             
     Storing 10 Integer Objects
     Storing Strings 
     Retrieve objects using an Iterator:
     0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , Aman , Raman , Manjeet Singh , Salman Khan , 
     Index of Raman is: 10
     New Sub-List [Raman, Manjeet Singh, Salman Khan]
     New Reversed List : [Salman Khan, Manjeet Singh, Raman]
     Is Sub-List empty? false
     Are Lists A and B equal? false
     ************List A (Before) : [0, 1, 2, 3, 4, 5, 6, 7, 8, Aman, Salman Khan, 
     Raman, Manjeet Singh]
     ************List A (after) : [5, 6, 2, 8, 1, Aman, Salman Khan, Manjeet Singh
     Raman, 3, 4, 7, 0]
     Are List’s A and B equal? false
     |Convert a List to an Array.|
     Array Element [0] = 5, Array Element [1] =6, Array Element [2] =2,Array  Element   [3] =8, Array Element [4] = 1, Array Element [5] = Aman, Array Element [6]    =Salman Khan, Array Element [7] =Manjeet SIngh, Array Element [8] = Raman, Array Element [9] =3, Array Element [10] =4, Array Element [11] = 7, Array Element [12] =0
     Remove (clear) Elements from List A.
     List A  (before) : [5, 6, 2, 8, 1, Aman, Salman Khan, Manjeet Singh, Raman, 3, 4, 7, 0]
     List A (after) : []

             

SETS

Set interface is derived from Collection interface. HashSet and LinkedHashSet are the concrete implementations of Set interface. Unlike ArrayList<E>,Vector<E> and LinkedList<E> collections objects, Set interface implementation do not allow dupli-cates. Its add() and addAll() methods will not store duplicates.
Set is exactly a Collection. There is no extra functionality. It just has different behaviour.

HashSet<E> and LinkedHashset<E> Classes

Both classes implement Set interface. These implementations use hash tables. A HashSet collection does not maintain insertion order of the elements. However, the oth-er class LinkedHashSet store elements in the insertion order. Set implementations use hashing to store elements and for lookup speed. HashSet<E> and LinkedHashSet<E> rely on implementations of the hashCode() and eqauls() methods of those classes of which objects are to be added. The hashCode() , method is used for hashing the ele-ments and equals() method is used for comparing the elements.
Implementation
import java.util.*;
public class SetsDemo
	{   public static void main(String args[])
      	          {   
		HashSet <String> S1 = new HashSet<String>();
		     S1.add("CPP");
 		     S1.add("Java"); 
		     S1.add("Struts");
		     S1.add("Springs");
		     System.out.println("List of All elements: ");
		     for(String s : S1)
		          System.out.println(s);
		   Set<String> S2 = new LinkedHashSet<String>();
		     S2.add("cpp");   S2.add("Java");   S2.add("Struts");
		     S2.add("Springs");
		     System.out.println("List of All elements");
		     for(String ss : S2)
		         System.out.println(ss);
	         }
	}
             
Output
	List of All elements:
	CPP
	Spring
	Struts
	Java
	List of All elements:
	CPP
	Java
	Struts
	Spring

             
import java.util.*;

	public class Set_allMethods {
	  public static void main(String args[]) 
	    {
		  String javaBatch[]={"Diya","Tanvi","Misha","Amir","Manmohan","Sandeep"}; 
		  String dotNet[]={"Sandeep","Vishav Deep","Diya","Rajesh","Misha"}; 
		  
		  HashSet <String> jb = new HashSet<String>(Arrays.asList(javaBatch));
		  HashSet <String> dn = new HashSet<String>(Arrays.asList(dotNet));
		     System.out.println("Java Batch : "+jb);
		     System.out.println("Dot Net Batch : "+ dn);
		     
		     HashSet <String> dnCopy=new HashSet<String>(dn);
		     dnCopy.retainAll(jb);
		     System.out.println("retainAll():"+dnCopy);
		     
		     HashSet <String> dnCopy2=new HashSet<String>(dn);
		     dnCopy2.removeAll(jb);
		     System.out.println("removeAll():"+dnCopy2);
		   
		     HashSet <String>all=new HashSet<String>();
		     all.addAll(jb);
		     all.addAll(dn);
		     System.out.println("addAll():"+all);
	  }
	}
             
Output
Java Batch : [Diya, Tanvi, Amir, Sandeep, Mohan, Misha]
Dot Net Batch :[Diya, Sandeep, Misha, Rajesh, Vishav]
retainAll():[Diya,Sandeep,Misha]
removeAll():[Rajesh, Vishav]
addAll();[Diya,Tanvi,Amir,Mohan,Sandeep,Misha,Rajesh,Vishav]

             

About the Author
Rajesh K. Bansal (SCJP-Sun Certified Java Programmer)
20 Years experience in Training & Development. Founder of realJavaOnline.com, loves coding in Java(J2SE, J2EE), C++,PHP, Python, AngularJS, Android,MERN Stack(MongoDB,Express,ReactJS,NodeJS). If you like tutorials and want to know more in depth about Java , buy his book "Real Java" available on amazon.in.
#Email : bcebti@gmail.com #Contact : 98722-46056
Available on Amazon
Card image cap
Under the guidance of Founder & Author of "realJavaOnline.com". M:9872246056
Card image cap