DAY 9

 JAVA COLLECTION FRAMEWORK

Collections in java is a framework that provides an architecture to store and manipulate the group of 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 represents a single unit of objects i.e. a group.

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.
hierarchy of collection framework

Methods of Collection interface

There are many methods declared in the Collection interface. They are as follows:
No.MethodDescription
1public boolean add(Object element)is used to insert an element in this collection.
2public boolean addAll(Collection c)is used to insert the specified collection elements in the invoking collection.
3public boolean remove(Object element)is used to delete an element from this collection.
4public boolean removeAll(Collection c)is used to delete all the elements of specified collection from the invoking collection.
5public boolean retainAll(Collection c)is used to delete all the elements of invoking collection except the specified collection.
6public int size()return the total number of elements in the collection.
7public void clear()removes the total no of element from the collection.
8public boolean contains(Object element)is used to search an element.
9public boolean containsAll(Collection c)is used to search the specified collection in this collection.
10public Iterator iterator()returns an iterator.
11public Object[] toArray()converts collection into array.
12public boolean isEmpty()checks if collection is empty.
13public boolean equals(Object element)matches two collection.
14public int hashCode()returns the hashcode number for collection.

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:

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


Java ArrayList class

Java ArrayList class hierarchyJava ArrayList class uses a dynamic array for storing the elements. It inherits AbstractList class and implements List interface.
The important points about Java ArrayList class are:
  • 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.

Hierarchy of ArrayList class

As shown in above diagram, Java ArrayList class extends AbstractList class which implements List interface. The List interface extends Collection and Iterable interfaces in hierarchical order.

ArrayList class declaration

Let's see the declaration for java.util.ArrayList class.
  1. public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable  

Constructors of Java ArrayList

ConstructorDescription
ArrayList()It is used to build an empty array list.
ArrayList(Collection c)It is used to build an array list that is initialized with the elements of the collection c.
ArrayList(int capacity)It is used to build an array list that has the specified initial capacity.

Methods of Java ArrayList

MethodDescription
void add(int index, Object element)It is used to insert the specified element at the specified position index in a list.
boolean addAll(Collection c)It is used to append all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator.
void clear()It is used to remove all of the elements from this list.
int lastIndexOf(Object o)It is used to return the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element.
Object[] toArray()It is used to return an array containing all of the elements in this list in the correct order.
Object[] toArray(Object[] a)It is used to return an array containing all of the elements in this list in the correct order.
boolean add(Object o)It is used to append the specified element to the end of a list.
boolean addAll(int index, Collection c)It is used to insert all of the elements in the specified collection into this list, starting at the specified position.
Object clone()It is used to return a shallow copy of an ArrayList.
int indexOf(Object o)It is used to return the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element.
void trimToSize()It is used to trim the capacity of this ArrayList instance to be the list's current size.

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.
For more information of java generics, click here Java Generics Tutorial.

Java ArrayList Example

  1. import java.util.*;  
  2. class TestCollection1{  
  3.  public static void main(String args[]){  
  4.   ArrayList<String> list=new ArrayList<String>();//Creating arraylist  
  5.   list.add("Ravi");//Adding object in arraylist  
  6.   list.add("Vijay");  
  7.   list.add("Ravi");  
  8.   list.add("Ajay");  
  9.   //Traversing list through Iterator  
  10.   Iterator itr=list.iterator();  
  11.   while(itr.hasNext()){  
  12.    System.out.println(itr.next());  
  13.   }  
  14.  }  
  15. }  
      OUTPUT:
       Ravi
       Vijay
       Ravi
       Ajay

Two ways to iterate the elements of collection in java

There are two ways to traverse collection elements:
  1. By Iterator interface.
  2. By for-each loop.
In the above example, we have seen traversing ArrayList by Iterator. Let's see the example to traverse ArrayList elements using for-each loop.

Iterating Collection through for-each loop

  1. import java.util.*;  
  2. class TestCollection2{  
  3.  public static void main(String args[]){  
  4.   ArrayList<String> al=new ArrayList<String>();  
  5.   al.add("Ravi");  
  6.   al.add("Vijay");  
  7.   al.add("Ravi");  
  8.   al.add("Ajay");  
  9.   for(String obj:al)  
  10.     System.out.println(obj);  
  11.  }  
  12. }  
      OUTPUT:
      Ravi
       Vijay
       Ravi
       Ajay


Java LinkedList class

Java LinkedList class hierarchy
Java LinkedList class uses doubly linked list to store the elements. It provides a linked-list data structure. It inherits the AbstractList class and implements List and Deque interfaces.
The important points about Java LinkedList are:
  • Java LinkedList class can contain duplicate elements.
  • Java LinkedList class maintains insertion order.
  • Java LinkedList class is non synchronized.
  • In Java LinkedList class, manipulation is fast because no shifting needs to be occurred.
  • Java LinkedList class can be used as list, stack or queue.

Hierarchy of LinkedList class

As shown in above diagram, Java LinkedList class extends AbstractSequentialList class and implements List and Deque interfaces.

Doubly Linked List

In case of doubly linked list, we can add or remove elements from both side.
java LinkedList class using doubly linked list

LinkedList class declaration

Let's see the declaration for java.util.LinkedList class.
  1. public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, Deque<E>, Cloneable, Serializable  

Constructors of Java LinkedList

ConstructorDescription
LinkedList()It is used to construct an empty list.
LinkedList(Collection c)It is used to construct a list containing the elements of the specified collection, in the order they are returned by the collection's iterator.

Methods of Java LinkedList

MethodDescription
void add(int index, Object element)It is used to insert the specified element at the specified position index in a list.
void addFirst(Object o)It is used to insert the given element at the beginning of a list.
void addLast(Object o)It is used to append the given element to the end of a list.
int size()It is used to return the number of elements in a list
boolean add(Object o)It is used to append the specified element to the end of a list.
boolean contains(Object o)It is used to return true if the list contains a specified element.
boolean remove(Object o)It is used to remove the first occurence of the specified element in a list.
Object getFirst()It is used to return the first element in a list.
Object getLast()It is used to return the last element in a list.
int indexOf(Object o)It is used to return the index in a list of the first occurrence of the specified element, or -1 if the list does not contain any element.
int lastIndexOf(Object o)It is used to return the index in a list of the last occurrence of the specified element, or -1 if the list does not contain any element.

Java LinkedList Example

  1. import java.util.*;  
  2. public class TestCollection7{  
  3.  public static void main(String args[]){  
  4.   
  5.   LinkedList<String> al=new LinkedList<String>();  
  6.   al.add("Ravi");  
  7.   al.add("Vijay");  
  8.   al.add("Ravi");  
  9.   al.add("Ajay");  
  10.   
  11.   Iterator<String> itr=al.iterator();  
  12.   while(itr.hasNext()){  
  13.    System.out.println(itr.next());  
  14.   }  
  15.  }  
  16. }  

Output:Ravi
       Vijay
       Ravi
       Ajay


Java HashSet class

Java HashSet class hierarchy
Java HashSet class is used to create a collection that uses a hash table for storage. It inherits the AbstractSet class and implements Set interface.
The important points about Java HashSet class are:
  • HashSet stores the elements by using a mechanism called hashing.
  • HashSet contains unique elements only.

Difference between List and Set

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

Hierarchy of HashSet class

The HashSet class extends AbstractSet class which implements Set interface. The Set interface inherits Collection and Iterable interfaces in hierarchical order.

HashSet class declaration

Let's see the declaration for java.util.HashSet class.
  1. public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, Serializable  

Constructors of Java HashSet class:

ConstructorDescription
HashSet()It is used to construct a default HashSet.
HashSet(Collection c)It is used to initialize the hash set by using the elements of the collection c.
HashSet(int capacity)It is used to initialize the capacity of the hash set to the given integer value capacity. The capacity grows automatically as elements are added to the HashSet.

Methods of Java HashSet class:

MethodDescription
void clear()It is used to remove all of the elements from this set.
boolean contains(Object o)It is used to return true if this set contains the specified element.
boolean add(Object o)It is used to adds the specified element to this set if it is not already present.
boolean isEmpty()It is used to return true if this set contains no elements.
boolean remove(Object o)It is used to remove the specified element from this set if it is present.
Object clone()It is used to return a shallow copy of this HashSet instance: the elements themselves are not cloned.
Iterator iterator()It is used to return an iterator over the elements in this set.
int size()It is used to return the number of elements in this set.

Java HashSet Example

  1. import java.util.*;  
  2. class TestCollection9{  
  3.  public static void main(String args[]){  
  4.   //Creating HashSet and adding elements  
  5.   HashSet<String> set=new HashSet<String>();  
  6.   set.add("Ravi");  
  7.   set.add("Vijay");  
  8.   set.add("Ravi");  
  9.   set.add("Ajay");  
  10.   //Traversing elements  
  11.   Iterator<String> itr=set.iterator();  
  12.   while(itr.hasNext()){  
  13.    System.out.println(itr.next());  
  14.   }  
  15.  }  
  16. }  

   OUTPUT:
       Ajay
       Vijay
       Ravi

Java LinkedHashSet class

Java HashSet class hierarchy
Java LinkedHashSet class is a Hash table and Linked list implementation of the set interface. It inherits HashSet class and implements Set interface.
The important points about Java LinkedHashSet class are:
  • Contains unique elements only like HashSet.
  • Provides all optional set operations, and permits null elements.
  • Maintains insertion order.

Hierarchy of LinkedHashSet class

The LinkedHashSet class extends HashSet class which implements Set interface. The Set interface inherits Collection and Iterable interfaces in hierarchical order.



Example of LinkedHashSet class:

  1. import java.util.*;  
  2. class TestCollection10{  
  3.  public static void main(String args[]){  
  4.   LinkedHashSet<String> al=new LinkedHashSet<String>();  
  5.   al.add("Ravi");  
  6.   al.add("Vijay");  
  7.   al.add("Ravi");  
  8.   al.add("Ajay");  
  9.   Iterator<String> itr=al.iterator();  
  10.   while(itr.hasNext()){  
  11.    System.out.println(itr.next());  
  12.   }  
  13.  }  
  14. }  
   OUTPUT:
       Ravi
       Vijay
       Ajay

Java TreeSet class

TreeSet class hierarchy
Java TreeSet class implements the Set interface that uses a tree for storage. It inherits AbstractSet class and implements NavigableSet interface. The objects of TreeSet class are stored in ascending order.
The important points about Java TreeSet class are:
  • Contains unique elements only like HashSet.
  • Access and retrieval times are quiet fast.
  • Maintains ascending order.

Hierarchy of TreeSet class

As shown in above diagram, Java TreeSet class implements NavigableSet interface. The NavigableSet interface extends SortedSet, Set, Collection and Iterable interfaces in hierarchical order.

Java TreeSet Example

  1. import java.util.*;  
  2. class TestCollection11{  
  3.  public static void main(String args[]){  
  4.   //Creating and adding elements  
  5.   TreeSet<String> al=new TreeSet<String>();  
  6.   al.add("Ravi");  
  7.   al.add("Vijay");  
  8.   al.add("Ravi");  
  9.   al.add("Ajay");  
  10.   //Traversing elements  
  11.   Iterator<String> itr=al.iterator();  
  12.   while(itr.hasNext()){  
  13.    System.out.println(itr.next());  
  14.   }  
  15.  }  
  16. }  
Output:
Ajay
Ravi
Vijay

Java Queue Interface

Java Queue interface orders the element in FIFO(First In First Out) manner. In FIFO, first element is removed first and last element is removed at last.

PriorityQueue class

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

Java PriorityQueue Example

  1. import java.util.*;  
  2. class TestCollection12{  
  3. public static void main(String args[]){  
  4. PriorityQueue<String> queue=new PriorityQueue<String>();  
  5. queue.add("Amit");  
  6. queue.add("Vijay");  
  7. queue.add("Karan");  
  8. queue.add("Jai");  
  9. queue.add("Rahul");  
  10. System.out.println("head:"+queue.element());  
  11. System.out.println("head:"+queue.peek());  
  12. System.out.println("iterating the queue elements:");  
  13. Iterator itr=queue.iterator();  
  14. while(itr.hasNext()){  
  15. System.out.println(itr.next());  
  16. }  
  17. queue.remove();  
  18. queue.poll();  
  19. System.out.println("after removing two elements:");  
  20. Iterator<String> itr2=queue.iterator();  
  21. while(itr2.hasNext()){  
  22. System.out.println(itr2.next());  
  23. }  
  24. }  

Comments

Popular posts from this blog

Day 7

Industrial training in CDAC