CollectionFramework-Part-1 In Java



Collection Framework:
The Java collections framework (JCF) is a set of classes and interfaces that implement commonly reusable collection data structures.
Collection framework allow us to manipulate and store group of object.
Collection Interface and classes are present in Java.utill package.

Here Interfaces are

·      Iterable
·      Collection
·      Set
·      Map
·      List
·      Queue

Remaining all are class
  • Hash Map
  • Linked Hash Map
  • Tree Map
  • Hash Map
  • Linked Hash Map
  • Tree Map
  • Array List
  • Linked List
  • Vector
  • Priority Queue





Array List: -

Array List is class in Java. It allows us to store multiple objects.

Points to Note: -

·      Array list is dynamic array, which means it will grow and shrink automatically.
·      Array list allows us to store duplicate elements.
·      Array list store data based on index.
·      Array list internally usages array.
·      Array list maintains insertion order.
·      Array list are not thread safe (not synchronized).
·      Manipulation is slow because a lot of shifting needs to be occurred if any    element is removed from the Array list.
·      Retrievals is fast in Array list.
·      Array list allows us to store any kind of data.

Arrays List Methods

·      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.

      Array list Example:

      In this example we can store any data type.

import java.util.*;

public class Example3 {

            public static void main(String[] args) {
                        List list = new ArrayList();
                        list.add(2);
                        list.add("2");
                        list.add("test");
                        list.add(true);
                        list.add('c');
                        list.add(9.80);
                        System.out.println(list);
            }
}
       Output: -
      [2, 2, test, true, c, 9.8]
      In Above example we are creating reference of List interface and object of Array  List. So that we can use all method of List interface.

    Note: -
·      In Below example we can store only one type of object in Array List.
·      To store only one type of object, we need to write type of object in angle bracket.
·      Below Example I am writing object type as Integer in angle bracket so that we can store only integer object, if we try to add other object we will get compile time error.


import java.util.*;
public class Example3 {
           
            public static void main(String[] args) {
      List<Integer> list = new ArrayList<Integer>();
      list.add(2);
      list.add(2);
      list.add(8);
      list.add(2);
      list.add(9);
      System.out.println(list);
            }          
}
output: -
[2, 2, 8, 2, 9]


 Get Method to get data from Array List

import java.util.*;

public class Example3 {

            public static void main(String[] args) {
                        List<Integer> list = new ArrayList<>();
                        list.add(1);
                        list.add(10);
                        list.add(8);
                        list.add(6);
                        for(int i =0; i<list.size();i++){
                                    System.out.println(list.get(i));
                        }
            }
}

in above example we are using get method to get the data from array list.
Get Method will take index to fetch the data from array list.


Add All Method

/**
 * Inserts all of the elements in the specified collection into this
 * list at the specified position (optional operation).  Shifts the
 * element currently at that position (if any) and any subsequent
 * elements to the right (increases their indices).  The new elements
 * will appear in this list in the order that they are returned by the
 * specified collection's iterator.  The behavior of this operation is
 * undefined if the specified collection is modified while the
 * operation is in progress.  (Note that this will occur if the specified
 * collection is this list, and it's nonempty.)
*/

import java.util.*;

public class Example3 {

            public static void main(String[] args) {
                        List<Integer> list = new ArrayList<>();
                        list.add(1);
                        list.add(10);
                        list.add(8);
                        list.add(6);
                        list.add(60);
                       
                        List<Integer> list1 = new ArrayList<>();
                        list1.add(80);
                        list1.add(60);
                       
                        list.addAll(list1);
                       
                        System.out.println(list);
            }
}
// OutPut:-[1, 10, 8, 6, 60, 80, 60]

Remove All Method

/**
 * Retains only the elements in this list that are contained in the
 * specified collection (optional operation).  In other words, removes
 * from this list all of its elements that are not contained in the
 * specified collection.
 */
import java.util.*;

public class Example3 {

            public static void main(String[] args) {
                        List<Integer> list = new ArrayList<>();
                        list.add(1);
                        list.add(10);
                        list.add(8);
                        list.add(6);
                        list.add(60);
                       
                        List<Integer> list1 = new ArrayList<>();
                        list1.add(80);
                        list1.add(60);
                       
                        // removeAll method is use to remove all matching data from first collection
                       
                        list.removeAll(list1);
                       
                        System.out.println(list);
            }
}
// OutPut:-[1, 10, 8, 6]

Retain All Method
/**
 * Retains only the elements in this list that are contained in the
 * specified collection (optional operation).  In other words, removes
 * from this list all of its elements that are not contained in the
 * specified collection.
 */

import java.util.*;

public class Example3 {

            public static void main(String[] args) {
                        List<Integer> list = new ArrayList<>();
                        list.add(1);
                        list.add(10);
                        list.add(8);
                        list.add(6);
                        list.add(60);
                       
                        List<Integer> list1 = new ArrayList<>();
                        list1.add(80);
                        list1.add(60);

                        list.retainAll(list1);
                       
                        System.out.println(list);
            }
}
// OutPut:-[60]


clear Method
/**
 * Removes all of the elements from this list (optional operation).
 * The list will be empty after this call returns.
 */
import java.util.*;

public class Example3 {

     public static void main(String[] args) {
         List<Integer> list = new ArrayList<>();
         list.add(1);
         list.add(10);
         list.add(8);
         list.add(6);
         list.add(60);
        
         List<Integer> list1 = new ArrayList<>();
         list1.add(80);
         list1.add(60);

         list.clear();
        
         System.out.println(list);
     }
}
// Output:-[]

Size method
/**
 * Returns the number of elements in this list.
 */
import java.util.*;

public class Example3 {

            public static void main(String[] args) {
                        List<Integer> list = new ArrayList<Integer>();
                        list.add(1);
                        list.add(10);
                        list.add(8);
                        list.add(6);
                        list.add(60);
                       
                        System.out.println(list.size());
                       
            }
}

// OutPut:-5

Linked List in Java

Points to Note:
·      Linked List is class, which will allow us to store and manipulate groups of data.
·      It allows us to store duplicate objects
·      It will grow dynamically on run time
·      It maintains insertion order
·      It is not thread safe (non synchronized)
·      It usages node to store the data.
·      Data retrieval is slow in linked list.
·      Manipulation is fast, due to no shifting operation happens.

In this example we can store all objects type

import java.util.*;

public class Example3 {

            public static void main(String[] args) {
                        List list = new LinkedList<>();
                        list.add(1);
                        list.add(10.990);
                        list.add(true);
                        list.add("6");
                        list.add("Test");                 
                        System.out.println(list);
            }
}
// Output: -[1, 10.99, true, 6, Test]

In this example we can store only Integer objects type, since we are restricting Object type by writing in angle bracket.

import java.util.*;

public class Example3 {

            public static void main(String[] args) {
                        List<Integer> list = new LinkedList<Integer>();
                        list.add(1);
                        list.add(10);
                        list.add(8);
                        list.add(6);
                        list.add(60);             
                        System.out.println(list);
            }
}
// Output: - [1, 10, 8, 6, 60]

get Method

/**
 * Returns the element at the specified position in this list.
*/

import java.util.*;

public class Example3 {

            public static void main(String[] args) {
                        List<Integer> list = new LinkedList<Integer>();
                        list.add(1);
                        list.add(10);
                        list.add(8);
                        list.add(6);
                        list.add(60);
                       
                        System.out.println(list.get(2));

                        //System.out.println(list);
            }
}
// Output:-8

Add All Method

/**
 * Inserts all of the elements in the specified collection into this
 * list at the specified position (optional operation).  Shifts the
 * element currently at that position (if any) and any subsequent
 * elements to the right (increases their indices).  The new elements
 * will appear in this list in the order that they are returned by the
 * specified collection's iterator.  The behavior of this operation is
 * undefined if the specified collection is modified while the
 * operation is in progress.  (Note that this will occur if the specified
 * collection is this list, and it's nonempty.)
*/

import java.util.*;

public class Example3 {

            public static void main(String[] args) {
                        List<Integer> list = new LinkedList<>();
                        list.add(1);
                        list.add(10);
                        list.add(8);
                        list.add(6);
                        list.add(60);
                       
                        List<Integer> list1 = new LinkedList<>();
                        list1.add(80);
                        list1.add(60);
                       
                        list.addAll(list1);
                       
                        System.out.println(list);
            }
}
// OutPut:-[1, 10, 8, 6, 60, 80, 60]

Remove All Method

/**
 * Retains only the elements in this list that are contained in the
 * specified collection (optional operation).  In other words, removes
 * from this list all of its elements that are not contained in the
 * specified collection.
 */
import java.util.*;

public class Example3 {

            public static void main(String[] args) {
                        List<Integer> list = new LinkedList<>();
                        list.add(1);
                        list.add(10);
                        list.add(8);
                        list.add(6);
                        list.add(60);
                       
                        List<Integer> list1 = new LinkedList<>();
                        list1.add(80);
                        list1.add(60);
                       
                        // removeAll method is use to remove all matching data from first collection
                       
                        list.removeAll(list1);
                       
                        System.out.println(list);
            }
}
// OutPut:-[1, 10, 8, 6]

Retain All Method
/**
 * Retains only the elements in this list that are contained in the
 * specified collection (optional operation).  In other words, removes
 * from this list all of its elements that are not contained in the
 * specified collection.
 */

import java.util.*;

public class Example3 {

            public static void main(String[] args) {
                        List<Integer> list = new LinkedList<>();
                        list.add(1);
                        list.add(10);
                        list.add(8);
                        list.add(6);
                        list.add(60);
                       
                        List<Integer> list1 = new LinkedList<>();
                        list1.add(80);
                        list1.add(60);

                        list.retainAll(list1);
                       
                        System.out.println(list);
            }
}
// OutPut:-[60]


clear Method
/**
 * Removes all of the elements from this list (optional operation).
 * The list will be empty after this call returns.
 */
import java.util.*;

public class Example3 {

     public static void main(String[] args) {
         List<Integer> list = new LinkedList<>();
         list.add(1);
         list.add(10);
         list.add(8);
         list.add(6);
         list.add(60);
        
         List<Integer> list1 = new LinkedList<>();
         list1.add(80);
         list1.add(60);

         list.clear();
        
         System.out.println(list);
     }
}
// Output:-[]


Size method

/**
 * Returns the number of elements in this list.
 */
import java.util.*;

public class Example3 {

            public static void main(String[] args) {
                        List<Integer> list = new LinkedList<Integer>();
                        list.add(1);
                        list.add(10);
                        list.add(8);
                        list.add(6);
                        list.add(60);
                       
                        System.out.println(list.size());
                       
            }
}

// OutPut:-5

ArrayList Vs LinkedList


ArrayList LinkedList
1) ArrayList internally uses dynamic array to store the elements. LinkedList internally uses doubly linked list to store the elements.
2) Manipulation with ArrayList is slow because it internally uses array. If any element is removed from the array, all the bits are shifted in memory. Manipulation with LinkedList is faster than ArrayList because it uses doubly linked list so no bit shifting is required in memory.
3) ArrayList class can act as a list only because it implements List only. LinkedList class can act as a list and queue both because it implements List and Deque interfaces.
4) ArrayList is better for storing and accessing data. LinkedList is better for manipulating data.

Vector in Java

Points to Note:
·      Vector is class, which will allow us to store and manipulate groups of data.
·      It allows us to store duplicate objects
·      It will grow dynamically on run time
·      It maintains insertion order
·      It is thread safe (non synchronized)

In this example we can store all objects type

import java.util.*;

public class Example3 {

            public static void main(String[] args) {
                        List list = new Vecrot<>();
                        list.add(1);
                        list.add(10.990);
                        list.add(true);
                        list.add("6");
                        list.add("Test");                 
                        System.out.println(list);
            }
}
// Output: -[1, 10.99, true, 6, Test]

In this example we can store only Integer objects type, since we are restricting Object type by writing in angle bracket.

import java.util.*;

public class Example3 {

            public static void main(String[] args) {
                        List<Integer> list = new Vector<Integer>();
                        list.add(1);
                        list.add(10);
                        list.add(8);
                        list.add(6);
                        list.add(60);             
                        System.out.println(list);
            }
}
// Output: - [1, 10, 8, 6, 60]

get Method

/**
 * Returns the element at the specified position in this list.
*/

import java.util.*;

public class Example3 {

            public static void main(String[] args) {
                        List<Integer> list = new Vector<Integer>();
                        list.add(1);
                        list.add(10);
                        list.add(8);
                        list.add(6);
                        list.add(60);
                       
                        System.out.println(list.get(2));

                        //System.out.println(list);
            }
}
// Output: -8

Add All Method

/**
 * Inserts all of the elements in the specified collection into this
 * list at the specified position (optional operation).  Shifts the
 * element currently at that position (if any) and any subsequent
 * elements to the right (increases their indices).  The new elements
 * will appear in this list in the order that they are returned by the
 * specified collection's iterator.  The behavior of this operation is
 * undefined if the specified collection is modified while the
 * operation is in progress.  (Note that this will occur if the specified
 * collection is this list, and it's nonempty.)
*/

import java.util.*;

public class Example3 {

            public static void main(String[] args) {
                        List<Integer> list = new Vector<>();
                        list.add(1);
                        list.add(10);
                        list.add(8);
                        list.add(6);
                        list.add(60);
                       
                        List<Integer> list1 = new Vector<>();
                        list1.add(80);
                        list1.add(60);
                       
                        list.addAll(list1);
                       
                        System.out.println(list);
            }
}
// OutPut:-[1, 10, 8, 6, 60, 80, 60]

Remove All Method

/**
 * Retains only the elements in this list that are contained in the
 * specified collection (optional operation).  In other words, removes
 * from this list all of its elements that are not contained in the
 * specified collection.
 */
import java.util.*;

public class Example3 {

            public static void main(String[] args) {
                        List<Integer> list = new Vector<>();
                        list.add(1);
                        list.add(10);
                        list.add(8);
                        list.add(6);
                        list.add(60);
                       
                        List<Integer> list1 = new Vector<>();
                        list1.add(80);
                        list1.add(60);
                       
                        // removeAll method is use to remove all matching data from first collection
                       
                        list.removeAll(list1);
                       
                        System.out.println(list);
            }
}
// OutPut:-[1, 10, 8, 6]

Retain All Method
/**
 * Retains only the elements in this list that are contained in the
 * specified collection (optional operation).  In other words, removes
 * from this list all of its elements that are not contained in the
 * specified collection.
 */

import java.util.*;

public class Example3 {

            public static void main(String[] args) {
                        List<Integer> list = new Vector<>();
                        list.add(1);
                        list.add(10);
                        list.add(8);
                        list.add(6);
                        list.add(60);
                       
                        List<Integer> list1 = new Vector<>();
                        list1.add(80);
                        list1.add(60);

                        list.retainAll(list1);
                       
                        System.out.println(list);
            }
}
// OutPut:-[60]



clear Method
/**
 * Removes all of the elements from this list (optional operation).
 * The list will be empty after this call returns.
 */
import java.util.*;

public class Example3 {

     public static void main(String[] args) {
         List<Integer> list = new Vector<>();
         list.add(1);
         list.add(10);
         list.add(8);
         list.add(6);
         list.add(60);
        
         List<Integer> list1 = new Vector<>();
         list1.add(80);
         list1.add(60);

         list.clear();
        
         System.out.println(list);
     }
}
// Output:-[]


Size method
/**
 * Returns the number of elements in this list.
 */
import java.util.*;

public class Example3 {

            public static void main(String[] args) {
                        List<Integer> list = new Vector<Integer>();
                        list.add(1);
                        list.add(10);
                        list.add(8);
                        list.add(6);
                        list.add(60);
                       
                        System.out.println(list.size());
                       
            }
}

// OutPut:-5



Iterators in Java

Iterator is used to iterator over collection of objects.
Iterator is interface.

package Test;
import java.util.ArrayList;
import java.util.Iterator;
public class Example2 {
           
      /**
     * Returns { true} if the iteration has more elements.
     * (In other words, returns {true} if {next} would
     * return an element rather than throwing an exception.)
     *
     * return {code true} if the iteration has more elements
     */
            public static void main(String[] args) {
                        ArrayList<Integer> array = new ArrayList<Integer>();
                        array.add(3);
                        array.add(4);
                        array.add(5);
                       
                        Iterator<Integer> itr = array.iterator();
                        while(itr.hasNext()){
                                    System.out.println(itr.next());
                        }
            }          
}
/*
Output: -
3
4
5
*/


Iterator Methods
·      boolean hasNext();
·      E next ();
·      void remove ();

boolean   hasNext()
·      Returns true if the iteration has more elements.

E    next ()
·      Returns the next element in the iteration.

void   remove ()
·      Removes from the underlying collection the last element returned by this iterator (optional operation).

boolean hasNext()
·      Returns true if the iteration has more elements. (In other words, returns true if next () would return an element rather than throwing an exception.)
·      Returns: true if the iteration has more elements

Methods in More Details:

E next ()
·      Returns the next element in the iteration.
·      Returns: the next element in the iteration
·      Throws:NoSuchElementException - if the iteration has no more elements

void remove ()
·      Removes from the underlying collection the last element returned by this iterator (optional operation). This method can be called only once per call to next ().
·      The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method.
·      Throws:UnsupportedOperationException - if the remove operation is not supported by this iterator.
·      IllegalStateException - if the next method has not yet been called, or the remove method has already been called after the last call to the next method.

Example2: Iterate over Linked List

package Test;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
public class Example2 {
            public static void main(String[] args) {
                        List<Integer> array = new LinkedList<Integer>();
                        array.add(3);
                        array.add(4);
                        array.add(5);
                       
                        Iterator<Integer> itr = array.iterator();
                        while(itr.hasNext()){
                                    System.out.println(itr.next());
                        }
            }          
}




Comments

  1. Any how collection is an interface, how do we get where all these methods signatures, how do we see them. As I know iterable is parent for collections, collection is child of collections, now what we are doing is implementing collection. How do we implement whitout knowing method signatures. dont say us we can use javap or api docs we wanted them practical implementation, what do you say, thanks if my question is wrong leave it.

    ReplyDelete
  2. Good Post! Thank you so much for sharing the nice post, it was so good to read and useful to improve
    Java Training in Electronic City

    ReplyDelete
  3. Nice work Sir, I appreciate your work also please check my work. best stock market course in delhi

    ReplyDelete

Post a Comment

Popular posts from this blog

CollectionFramework-Part-2 In Java

OOPs concepts In Java