Collection Frameworks

Disadvantage of Arrays:
  • It has fixed size
  • It does not provide any API to perform searching, sorting on Elements of the Arrays.
  • It can only store similar data types
  • Take more time to delete and insert in the middle

To overcome Array disadvantage we have to go for Collection Framework classes

Advantage of Collection:
  • It is dynamic
  • It provide API to perform sorting, searching, inserting and deleting elements
  • It can store same or different data types
  • It uses best algorithms to delete and insert in the middle

Collection Hierarchy:



































package com.collection;

import java.util.*;

public class ArrayListDemo {
    public static void main(String[] args) {
        System.out.println("--------------------ArrayList--------------------");
        ArrayList al = new ArrayList(); //Store duplicates and maintains insertion Order
        
        al.add(10);
        al.add(12.5);
        al.add(true);
        al.add(null);
        al.add(null);
        al.add('A');
        al.add(12.5);
        al.add("Array List");
        System.out.println("Total Objects in ArrayList is: " + al.size());    //8
        for (Object object : al) {
            System.out.println(object);
        }
        System.out.println("--------------------HashSet--------------------");
        HashSet hs = new HashSet(al);    //duplicates not allowed and maintains no insertion Order
        System.out.println("Total Objects in HashSet is: " + hs.size());    //6
        for (Object object : hs) {
            System.out.println(object);
        }
        System.out.println("--------------------LinkedHashSet--------------------");
        LinkedHashSet lhs = new LinkedHashSet();    //duplicates not allowed and maintains insertion Order
        lhs.addAll(al);
        System.out.println("Total Objects in LinkedHashSet is: " + lhs.size());    //6
        for (Object object : lhs) {
            System.out.println(object);
        }
    }
}

Iterator and ListIterator:
package com.collection;

import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Vector;

public class IteratorDemo {

    public static void main(String[] args) {
        List states = new Vector();
        states.add("Karnataka");
        states.add(1, "Andhra Pradesh");
        states.add("Uttar Pradesh");
        states.add("Maharashya");
        states.add(2, "Kerala");
        System.out.println(states);
        System.out.println("--------------------Iterator------------------------------");
        Iterator itr = states.iterator();
        while(itr.hasNext()){
            String state = itr.next();        //To Retrieve element
            if(state.equals("Kerala")){
                itr.remove();                //To remove an element
            } else {
                System.out.print(state + " ");
            }
        }
        
        System.out.println("\n--------------------ListIterator---------------------");
        ListIterator litr = states.listIterator();
        while(litr.hasNext()){
            String state =litr.next();            //To  retrieve an element
            if(state.equals("Andhra Pradesh")){
                litr.set("Telangana");            //To Update an current element
                litr.add("Madhya Pradesh");        //To add new element
                System.out.print(state + " ");
            } else if(state.equals("Maharashya")){
                litr.remove();                    //To remove current element
            } else {
                System.out.print(state + " ");
            }
        }
        System.out.println("\n-----------------------------------------------------");
        System.out.println(states);
        System.out.println("-----------------------------------------------------");
        System.out.println("--------------------for loop-------------------------");
        for (int i = 0; i < states.size(); i++) {
            System.out.print(states.get(i) + " ");
        }
        System.out.println("\n--------------------for each loop-------------------------");
        for (String state : states) {
            System.out.print(state + " ");
        }
    }
}


Difference between List and Set:
List Set
It can store duplicates It can not store duplicates
Insertion Order is preserved Insertion Order is not preserved except LinkedHashSet
List interface provides extra methods related to index Set interface does not provides extra methods
It can store multiple null value It can only store one null value

Difference between Iterator and ListIterator:
Iterator ListIterator
It is universal cursor It is not universal cursor
It have 3 methods It have 9 methods
hasNext(), next() and remove() method hasNext(), hasPrevious(), previous(), next(), previousIndex(), nextIndex(), remove(), add(Object obj) and set() method
It is used  to traverse elements for Set, List, Queue and Map using iterator() method of Collection Interface It is used to traverse elements for List and it's sub-classes using listIterator() method of List Interface
It can traverse collection of object in uni-direction  It can traverse collection of object in bi-direction

Difference between Iterator and Enumeration:
Iterator Enumeration
It is universal cursor It is not universal cursor
It have 3 methods It have 2 methods
hasNext(), next() and remove() methods hasMoreElements() and nextElement() methods
It is used  to traverse legacy and non-legacy classes e.g. ArrayList, LinkedList, HashSet, etc. classes using iterator() method of Collection Interface It is used to traverse elements for legacy classes e.g. Vector, Hashtable and Properties using elements() method of Enumeration Interface
It throws Exception when two or more threads are try to modify the collection It will not throw any exception because it thread safe and it does not have any remove method

Difference between Collection and Collections:
Collection Collections
It is a base interface for Set, List and Queue interface It is an utility class
It has abstract and default methods It has static methods
It have add, addAll, remove, removeAll,  size, contains, containsAll, retainAll isEmpty, iterator and  toArray methods It have sort, synchronizedList, synchronizedSet, synchronizedMap, unmodifiableMap, unmodifiableList, unmodifiableSet, min, max, reverse, shuffle and binarySearch methods
It is used to provide structure for collection related classes It is used to perform operation on collection of objects

Difference between ArrayList and LinkedList:
ArrayList LinkedList
It is class and implemented based on dynamic array It is a class and implemented based on doubly linked list
It is mostly used when frequent operations is retrieval and manipulated sequentially It is mostly used when the frequent operations is manipulation like update and delete
It implements RandomAccess interface so retrieval is faster than LinkedList It implements Queue so it have queue related methods and retrieval is slower than ArrayList
It generally takes less storage space It generally takes more storage space

Difference between ArrayList and Vector:
ArrayList Vector
It is not synchronized but can be made by Collections.synchronizedList(List list) method It is synchronized means it is thread safe.
It is not legacy class It is legacy class means Vector class is present since JDK 1.0
It grow its size by half (50%) Its grow its size by double (100%)
It is faster than Vector because its methods are not synchronized It is slower than ArrayList because methods are synchronized

No comments:

Post a Comment