Header Ads

Collection Framework


Collections in java is a framework that provides an architecture to store and manipulate the group of
the objects. All the operations that you perform on a data such as searching, sorting, insertion, manipulation, deletion etc. can be performed by Java Collections.

Java Collection simply means a single unit of objects. Java Collection framework provides many interfaces (Set, List, Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet etc). Collection in java represents a single unit of objects i.e. a group.

What is framework in java
  • provides readymade architecture.
  • represents set of classes and interface.
  • is optional
What is Collection framework: Collection framework represents a unified architecture for storing and manipulating group of objects.. It has: 1. Interfaces and its implementations i.e. classes 2. Algorithm.

Hierarchy of Collection Framework: Let us see the hierarchy of collection framework. The java.util package contains all the classes and interfaces for Collection framework

Methods of Collection interface

There are many methods declared in the Collection interface. They are as follows:

methods of collection interface

Iterator interface

Iterator interface provides the facility of iterating the elements in forward direction only.

Methods of Iterator interface

There are only three methods in the Iterator interface. They are:

1. public boolean hasNext() it returns true if iterator has more elements.
2. public object next() it returns the element and moves the cursor pointer to the next element.
3. public void remove() it removes the last elements returned by the iterator. It is rarely used

Java ArrayList class

Java ArrayList class uses a dynamic array for storing the elements. It extends AbstractList class and implements List interface.
Java ArrayList class can contain duplicate elements.
Java ArrayList class maintains insertion order.
Java ArrayList class is non synchronized.
Java ArrayList allows random access because array works at the index basis.
In Java ArrayList class, manipulation is slow because a lot of shifting needs to be occurred if any element is removed from the array list.

Java Non-Generic Vs Generic Collection

Java collection framework was non-generic before JDK 1.5. Since 1.5, it is generic. Java new generic collection allows you to have only one type of object in collection. Now it is type safe so typecasting is not required at run time..

Let's see the old non-generic example of creating java collection.
         
           1. ArrayList al=new ArrayList ();//creating old non-generic arraylist

Let's see the new generic example of creating java collection.

            1. ArrayList<String> al=new ArrayList<String>();//creating new generic arraylist

In generic collection, we specify the type in angular braces.. Now ArrayList is forced to have only specified type of objects in it. If you try to add another type of object, it gives compile time error.

Example of Java ArrayList class

Code

import java.util.*; 
class TestCollection1 
{ 
  public static void main(String args[]) 
  { 
    ArrayList<String> al=new ArrayList<String>();//creating arraylist 
    al.add("Ravi");//adding object in ArrayList 
    al.add("Vijay");
    al.add("Ravi"); 
    al.add("Ajay");
    Iterator itr=al.iterator();//getting Iterator from arraylist to traverse elements 
    while(itr.hasNext()) {
      System.out.println(itr.next()); 
    }
}
Output
               Ravi
               Vijay
                Ravi
                  Ajay

User-defined class objects in Java ArrayList

Code

class Student 
{ 
  int rollno;
  String name; 
  int age;  
  Student(int rollno,String name,int age)
  {
    this.rollno = rollno; 
    this.name=name; 
    this.age=age; 
   }
} 

import java.util.*; 
public class TestCollection3 
{
   public static void main(String args[]) 
   { 
      //Creating user-defined class objects 
      Student sl=new Student(101,,"Sonoo",23); 
      Student s2=new Student(102,,"Ravi",21); 
      Student s2=new Student(103,"Hanumat",25); 
		
      ArrayList<Student> al=new ArrayList<Student>();//creating arraylist 
      al.add(s1);//adding Student class object 
      al.add(s2); 
      al.add(s3); 

      Iterator itr=al.iterator(); 
      //traversing elements of ArrayList object 
      while(itr.hasNext()) 
      { 
        Student st = (Student)itr.next(); 
        System.out.println(st.rollno+" "+st.name+" "+st.age);
      }
   } 
} 
Output:

101   Sonoo   23
102   Ravi 21
103  Hanumat 25 

Example of addAll(Collection c) method

Code

import java.util.*; 
class TestCollection4 
{ 
   public static void main(String args[]) 
   { 
     ArrayList<String> al=new ArrayList<String>(); 
     al.add("Ravi"); 
     al.add("Vijay"); 
     al.add("Ajay"); 
		
     ArrayList<String> al2=new ArrayList<String>(); 
     al2.add("Sonoo"); 
     al2.add("Hanumat"); 
     al.addAll(al2); 
     Iterator itr=al.iterator(); 
     while(itr.hasNext()) 
     { 
        System.out.println(itr.next()); 
      } 
    }
} 
Output:
   Ravi
   Vijay
   Ajay
   Sonoo
   Hanumat

Example of removeAll() method

Code

import java.util.*;
class TestCollection5
{ 
  public static void main(String args[]) 
  { 
    ArrayList<String> al=new ArrayList<String>(); 
    al.add("Ravi"); 
    al.add("Vijay"); 
    al.add("Ajay"); 
 
    ArrayList<String> al2=new ArrayList<String>(); 
    al2.add("Ravi"); 
    al2.add("Hanumat"); 

    al.removeAll(al2); 

    System.out.println("iterating the elements after removing the elements of al2...");
    Iterator itr=al.iterator(); 
    while(itr.hasNext()){
      System.out.println(itr.next());
     } 
   }
} 
Output:

iterating the elements after removing the elements of al2…...
Vijay
Ajay

Example of retain All() method 

Code

import java.util.*; 
class TestCollection6 
{
   public static void main(String args[])
   { 
       ArrayList<String> al=new ArrayList<String>(); 
       al.add("Ravi"); 
       al.add("Vijay"); 
       al.add("Ajay"); 
       ArrayList<String> al2=new ArrayList<String>(); 
       al2.add("Ravi"); 
       al2.add("Hanumat"); 

       al.retainAll(al2); 

       System.out.println("iterating the elements after retaining the elements of al2..."); 
       Iterator itr=al.iterator(); 

       while(itr.hasNext()) 
       { 
         System.out.println(itr.next()); 
       } 
   } 
} 
Output:

iterating the elements after retaining the elements of al2...                                              
Ravi

Java LinkedList class

1. Java LinkedList class uses doubly linked list to store the elements. It extends the AbstractList class and implements List and Deque interfaces.
2. Java LinkedList class can contain duplicate elements.
3. Java LinkedList class maintains insertion order.
4. Java LinkedList class is non synchronized.
5. In Java LinkedList class, manipulation is fast because no shifting needs to be occurred.
6. Java LinkedList class can be used as list, stack or queue

Java LinkedList Example

Code

import java.util.*; 
public class TestCollection7 
{ 
  public static void main(String args[]) 
  { 
     LinkedList<String> al=new LinkedList<String>();          
     al.add("Ravi");
     al.add("Vijay");
     al.add("Ravi"); 
     al.add("Ajay"); 

     Iterator<String> itr=al.iterator(); 
     while(itr.hasNext()){ 
       System.out.println(itr.next()); 
     } 
   }
} 
Output
Ravi
Vijay
Ravi
Ajay

Example of ArrayList and LinkedList in Java

Let's see a simple example where we are using ArrayList and LinkedList both

Code

import java.util.*; 
class TestArrayLinked 
{
   public static void main(String args[]) 
   {
     List<String> al=new ArrayList<String>();//creating arraylist
     al.add("Ravi");//adding object in arraylist 
     al.add("Vijay"); 
     al.add("Ravi"); 
     al.add("Ajay"); 

     List<String> al2=new LinkedList<String>();//creating linkedlist
     al2.add("James");//adding object in linkedlist 
     al2.add("Serena"); 
     al2.add("Swati"); 
     al2.add("Junaid"); 

     System.out.println("arraylist: "+al); 
     System.out.println("linkedlist: "+al2); 
   }
} 

Output:

arraylist: [Ravi,Vijay,Ravi,Ajay]
linkedlist: [James,Serena,Swati,Junaid]

Java List Interface

List Interface is the subinterface of Collection. It contains methods to insert and delete elements in index basis. It is a factory of ListIterator interface.

Commonly used methods of List Interface - 

1. public void add(int index,Object element);
2. public boolean addAll(int index,Collection c);
3. public object get(int Index position);
4. public object set(int index,Object element);
5. public object remove(int index);
6. public ListIterator listIterator();
7. public ListIterator listIterator(int i);

Java ListIterator Interface

ListIterator Interface is used to traverse the element in backward and forward direction..

Commonly used methods of ListIterator Interface:

1. public boolean hasNext();
2. public Object next();
3. public boolean hasPrevious();
4. public Object previous();

Example of ListIterator Interface

Code

import java.util.*; 
public class TestCollection8 
{ 
  public static void main(String args[]) 
  { 
    ArrayList<String> al=new ArrayList<String>(); 
    al.add("Amit"); 
    al.add("Vijay"); 
    al.add("Kumar"); 
    al.add(1,"Sachin"); 

    System.out.println("element at 2nd position: "+al.get(2)); 

    ListIterator<String> itr=al.listIterator(); 

    System.out.println("traversing elements in forward direction...");
    while(itr.hasNext()){ 
      System.out.println(itr.next()); 
    } 
    System.out.println("traversing elements in backward direction...");
    while(itr.hasPrevious()){ 
      System.out.println(itr.previous()); 
    }
  }
} 
Output:
element at 2nd position: Vijay
traversing elements in forward direction....
Amit
Sachin
Vijay
Kumar
traversing elements in backward direction...
Kumar
Vijay
Sachin
Amit

Difference between ArrayList and LinkedList

ArrayList and LinkedList both implements List interface and maintains insertion order. Both are nor
synchronized classes. But there are many differences between ArrayList and LinkedList classes that are
given below.
difference between arraylist and linkedlist

Java HashSet class: It uses hashtable to store the elements. It extends AbstractSet class and implements Set interface. It contains unique elements only..

Difference between List and Set:

List can contain duplicate elements whereas Set contains unique elements only.

Java HashSet class
Example of HashSet class:

Code

import java.util.*; 
class TestCollection9 
{
    public static void main(String args[]) 
    {
      HashSet<String> al=new HashSet<String>();
      al.add("Ravi"); 
      al.add("Vijay"); 
      al.add("Ravi"); 
      al.add("Ajay"); 

      Iterator<String> itr=al.iterator(); 
      while(itr.hasNext()){ 
      System.out.println(itr.next()); 
     } 
   } 
} 
Output:
Ajay  
Vijay
Ravi

Java LinkedHashSet class:

1. contains unique elements only like HashSet. It extends HashSet class and implements Set interface.
2. maintains insertion order.

Java LinkedHashSet class

Example of LinkedHashSet class:

Code

import java.util.*; 
class TestCollection10 
{ 
  public static void main(String args[]) 
  {
     LinkedHashSet<String> al = new LinkedHashSet<String>();
     al.add("Ravi"); 
     al.add("Vijay"); 
     al.add("Ravi"); 
     al.add("Ajay"); 
   
     Iterator<String> itr=al.iterator();       
     while(itr.hasNext()) { 
       System.out.println(itr.next());
     }
   }
} 
Output:
Ravi
Vijay
 Ajay

Java TreeSet class

1. contains unique elements only like HashSet. The TreeSet class implements NavigableSet interface that extends the SortedSet interface.
2. maintains ascending order.

Hierarchy of TreeSet class:

Hierarchy of TreeSet

Example of TreeSet class:

Code

import java.util.*; 
class TestCollection11 
{ 
   public static void main(String args[]) 
   {
      TreeSet<String> al=new TreeSet<String>();          
      al.add("Ravi"); 
      al.add("Vijay"); 
      al.add("Ravi"); 
      al.add("Ajay"); 

      Iterator<String> itr=al.iterator();          
      while(itr.hasNext()){ 
           System.out.println(itr.next());
        }
     }
 } 
Output
Ajay
Ravi
Vijay 

Java Queue Interface

The Queue interface basically orders the element in FIFO(First In First Out)manner.

Methods of Queue Interface:

1.   public boolean add(object);
2.   public boolean offer(object);
3.   public remove();
4.   public poll(); pull
5.   public element();
6.   public peek();

PriorityQueue class:

The PriorityQueue class provides the facility of using queue. But it does not orders the elements in FIFO manner..

Example of PriorityQueue

Code

import java.util.*; 
class TestCollection 12 
{ 
  public static void main(String args[]) 
  { 
    PriorityQueue<String> queue=new PriorityQueue<String>();        
    queue.add("Amit"); 
    queue.add("Vijay"); 
    queue.add("Karan"); 
    queue.add("Jai"); 

    queue.add("Rahul");      
    System.out.println("head:"+queue.element()); 
    System.out.println("head:"+queue.peek());

    System.out.println("iterating the queue elements:");
    Iterator itr=queue.iterator();
    while(itr.hasNext()){
      System.out.println(itr.next());
     }
       
     queue.remove(); 
     queue.poll(); 

     System.out.println("after removing two elements:");
      Iterator<String> itr2=queue.iterator(); 
      while(itr2.hasNext()) { 
        System.out.println(itr2.next()); 
      }
   } 
} 
Output:
head:Amit
head:Amit
iterating the queue elements:
Amit
Jai
Karan
Vijay
Rahul
after removing two elements:
Karan
Rahul
Vijay

Java Map Interface

A map contains values based on the key i.e. key and value pair. Each pair is known as an entry. Map contains only unique elements.

Commonly used methods of Map interface

1.  public Object put(object key,Object value): is used to insert an entry in this map.
2.  public void putAll(Map map): is used to insert the specified map in this map.
3.  public Object remove(object key): is used to delete an entry for the specified key.
4.  public Object get(Object key): is used to return the value for the specified key.
5.  public boolean containsKey(Object key): is used to search the specified key from this map.
6.  public boolean containsValue(Object value):is used to search the specified value from this map.
7.   public Set keySet():returns the Set view containing all the keys.
8.  public Set entrySet():returns the Set view containing all the keys and values.

Entry

Entry is the subinterface of Map. So we will access it by Map. Entry name.. It provides methods to get key and value

Methods of Entry interface:
1.    public Object getKey(): is used to obtain key.
2.    public Object getValue():is used to obtain value.

Java HashMap class

A HashMap contains values based on the key.. It implements the Map interface and extends AbstractMap class.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.

Hierarchy of HashMap class:

Hierarchy of HashMap

Example of HashMap class:

Code

import java.util.*; 
class TestCollection13 
{ 
  public static void main(String args[]) 
  { 
     HashMap<Integer,String> hm=new HashMap<Integer,String>(); 

     hm.put(100,"Amit"); 
     hm.put(101,"Vijay"); 
     hm.put(102,"Rahul"); 
    
     for(Map.Entry m:hm.entrySet()){
         System.out.println(m.getKey()+" "+m.getValue()); 
     } 
   }
 } 
Output
102 Rahul
100 Amit
101 Vijay 

What is difference between HashSet and HashMap?

HashSet contains only values whereas HashMap contains entry(key and value).

Java LinkedHashMap class  
  • A LinkedHashMap contains values based on the key.. It implements the Map interface and extends HashMap class.
  • It contains only unique elements.
  • It may have one null key and multiple null values.
  • It is same as HashMap instead maintains insertion order.
Hierarchy of LinkedHashMap class:

Hierarchy of LinkedHashMap class

Example of LinkedHashMap class:

Code

import java.util.*; 
class TestCollection14 
{ 
  public static void main(String args[]) 
  { 
    LinkedHashMap<Integer,String> hm=new LinkedHashMap<Integer,String>(); 
    hm.put(100,"Amit");
    hm.put(101,"Vijay"); 
    hm.put(102," Rahul"); 
              
    for(Map.Entry m:hm.entrySet()){
       System.out.println(m.getKey()+" "+m.getValue());   
    } 
  } 
}

Output
100 Amit
101 Vijay
103 Rahul

Java TreeMap class

A TreeMap contains values based on the key. It implements the NavigableMap interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order.

Hierarchy of TreeMap class

Hierarchy of TreeMap

Example of TreeMap class

Code

import java.util.*; 
class TestCollection15{ 
  public static void main(String args[]) 
  { 
    TreeMap<Integer,String> hm=new TreeMap<Integer,String>(); 

    hm.put(100,"Amit"); 
    hm.put(102,"Ravi"); 
    hm.put(101,"Vijay"); 
    hm.put(103,"Rahul"); 

   for(Map.Entry m:hm.entrySet()){ 
     System.out.println(m.getKey()+" "+m.getValue()); 
    } 
  } 
} 
Output
100 Amit
101 Vijay
102 Ravi
103 Rahul

What is difference between HashMap and TreeMap?

1) HashMap is can contain one null key. TreeMap can not contain any null key.
2) HashMap maintains no order.              TreeMap maintains ascending order.

Java Hashtable class
  • A Hashtable is an array of list. Each list is known as a bucket. The position of bucket is identified by calling the hashcode() method. A Hashtable contains values based on the key. It implements the Map interface and extends Dictionary class.
  • It contains only unique elements.
  • It may have not have any null key or value.
  • It is synchronized.
Example of Hashtable:

Code

import java.util.*; 
class TestCollection16 
{ 
   public static void main(String args[]) 
   { 
   Hashtable<Integer,String> hm=new Hashtable<Integer,String>(); 

   hm.put(100,"Amit"); 
   hm.put(102,"Ravi"); 
   hm.put(101,"Vijay"); 
   hm.put(103,"Rahul"); 
        
   for(Map.Entry m:hm.entrySet()){ 
        System.out.println(m.getKey()+" "+m.getValue()); 
   } 
 } 
Output: 
103 Rahul
102 Ravi
101 Vijay
100 Amit

Difference between HashMap and Hashtable

HashMap and Hashtable both are used to store data in key and value form. Both are using hashing technique to store unique keys. But there are many differences between HashMap and Hashtable classes that are given below.

difference between HashMap and Hashtable

Sorting

We can sort the elements of:
1. String objects
2. Wrapper class objects
3. User-defined class objects

Collections class provides static methods for sorting the elements of collection. If collection elements are of Set type, we can use TreeSet. But We cannot sort the elements of List. Collections class provides methods for sorting the elements of List type elements.

Method of Collections class for sorting List elements

public void sort(List list): is used to sort the elements of List. List elements must be of Comparable type.

Note: String class and Wrapper classes implements the Comparable interface. So if you store the objects of string or wrapper classes, it will be Comparable.

Example of Sorting the elements of List that contains string objects

Code

import java.util.*; 
class TestSortl{ 
   public static void main(String args[]){ 
 
   ArrayList<String> al=new ArrayList<String>(); 
   al.add("Viru"); 
   al.add("Saurav"); 
   al.add("Mukesh"); 
   al.add("Tahir"); 
     
   Collections.sort(al); 
   Iterator itr=al.iterator(); 
   while(itr.hasNext()) { 
      System.out.println(itr.next()); 
    } 
  } 
} 
Output:
Mukesh
Saurav
Tahir
Vira

Example of Sorting the elements of List that contains Wrapper class objects

Code

import java.util.*; 
class TestSort2 
{ 
   public static void main(String args[]) 
   {
     ArrayList al=new ArrayList(); 
     al.add(Integer.valueOf(201)); 
     al.add(Integer.valueOf(101)); 
     al.add(230);//internally will be converted into objects as Integer.valueOf(230) 

      Collections.sort(al); 
    
      Iterator itr=al.iterator(); 
      while(itr.hasNext()) { 
          System.out.println(itr.next()); 
       } 
    } 
 } 
Output:
101
201
230

Comparable interface

Comparable interface is used to order the objects of user-defined class. This interface is found in java.lang package and contains only one method named compareTo(Object). It provide only single sorting sequence i.e. you can sort the elements on based on single datamember only. For instance it may be either rollno, name, age or anything else.

Syntax:

public int compareTo(Object obj): is used to compare the current object with the specified object.

We can sort the elements of:
1. String objects
2. Wrapper class objects
3. User-defined class objects

Collections class provides static methods for sorting the elements of collection. If collection elements are of Set type, we can use TreeSet. But We cannot sort the elements of List.Collections class provides methods for sorting the elements of List type elements.

Method of Collections class for sorting List elements

public void sort(List list): is used to sort the elements of List. List elements must be of Comparable type.

Note: String class and Wrapper classes implements the Comparable interface. So if you store the objects of string or wrapper classes, it will be Comparable.
Example of Sorting the elements of List that contains user-defined class objects on age basis

Student.java

Code

class Student implements Comparable 
{ 
  int rollno; 
  String name;
  int age; 
  Student(int rollno,String name, int age){ 
  this.rollno=rollno; 
  this.name=name;
  this.age=age; 
} 

public int compareTo(Object obj) 
{ 
  Student st (Student)obj; 
  if(age==st.age)
    return 0; 
  else if(age>st.age) 
    return 1; 
  else 
    return -1; 
  } 
} 
Simple.java

Code

import java.util.*; 
import java.io.*; 
   
class TestSort3 
{
   public static void main(String args[]) 
   {
      ArrayList al=new ArrayList(); 
      al.add(new Student(101,"Vijay",23)); 
      al.add(new Student(106,"Ajay",27)); 
      al.add(new Student(105,"Jai",21)); 
     
      Collections.sort(al); 
      Iterator itr=al.iterator();
      while(itr.hasNext()){ 
        Student st⇒(Student)itr.next(); 
        System.out.println(st.rollno+""+st.name+"'"+st.age); 
      }
   }
} 
Output
105 Jai 21
101 Vijay 23
106 Ajay 27

Difference between ArrayList and Vector

ArrayList and Vector both implements List interface and maintains insertion order. But there are many differences between ArrayList and Vector classes that are given below.

difference between ArrayList and Vector

Example of Java ArrayList

Let's see a simple example where we are using ArrayList to store and traverse the elements.

Code

import java.util.*; 
class Test Vector1 
{ 
  public static void main(String args[]) 
  {
    List<String> al=new ArrayList<String>();//creating arraylist
     al.add("Sonoo");//adding object in arraylist
     al.add("Michael"); 
     al.add("James"); 
     al.add("Andy"); 
     //traversing elements using Iterator 
     Iterator itr=al.iterator(); 
     while(itr.hasNext()) { 
        System.out.println(itr.next());
     }
   }
 }
Output
Sonoo
Michael
James
Andy

Example of Java Vector

Let's see a simple example of java Vector class that uses Enumeration interface.

Code

import java.util.*; 
class TestVector1 
{ 
   public static void main(String args[])
   {    
      Vector<String> v=new Vector<String>();//creating vector 
      v.add("umesh");//method of Collection 
      v.addElement("irfan");//method of Vector        
      v.addElement("kumar");
      //traversing elements using Enumeration 
      Enumeration e=v.elements();          
      while(e.hasMoreElements()){
         System.out.println(e.nextElement()); 
      }
    }
  }
Output:
umesh
irfan
kumar

No comments

Powered by Blogger.