Showing posts with label Java Collections. Show all posts
Showing posts with label Java Collections. Show all posts

Thursday, 1 February 2018

List in Collection

DashZin

It is the Child Interface of Collection. If we want to Represent a Group of Individual Objects where Duplicates are allowed and Insertion Order Preserved. Then we should go for List. We can Preserve Insertion Order and we can Differentiate Duplicate Object by using Index. Hence Index will Play Very Important Role in List.

Methods:
List Interface Defines the following Specific Methods.

1) void add(int index, Object o)

2) booleanaddAll(int index, Collection c)

3) Object get(int index)

4) Object remove(int index)

5) Object set(int index, Object new): To Replace the Element Present at specified Index with         provided Object and Returns Old Object.

6) intindexOf(Object o):Returns Index of 1st Occurrence of 'o'

7) intlastIndexOf(Object o)

8) ListIteratorlistIterator();

ArrayList: -
The Underlying Data Structure for ArrayList is Resizable Array ORGrowable Array. Duplicate Objects are allowed. Insertion Order is Preserved.  Heterogeneous Objects are allowed (Except TreeSet and TreeMap Everywhere Heterogeneous Objects are allowed).  null Insertion is Possible.

Constructors:
1)      ArrayList l = new ArrayList();
Creates an Empty ArrayList Object with Default Initial Capacity 10.  If ArrayList Reaches its Max Capacity then a New ArrayList Object will be Created with 
      2) ArrayList l = new ArrayList(intinitialCapacity);
           Creates an Empty ArrayList Object with specified Initial Capacity.


     3) ArrayList l = new ArrayList(Collection c); 

Example : -

importjava.util.ArrayList;
classArrayListDemo
 { 
public static void main(String[] args)
{
 ArrayList l = new ArrayList();
 l.add("A");
l.add(10);  
l.add("A");  
l.add(null);  
System.out.println(l); //[A, 10, A, null]  
l.remove(2);   System.out.println(l); //[A, 10, null]
l.add(2,"M"); 
 l.add("N");  
System.out.println(l); //[A, 10, M, null, N]
 }
 }

·         Usually we can Use Collections to Hold and Transfer Data (Objects) form One Location to Another Location. 
·         To Provide Support for this Requirement Every Collection Class Implements Serializable and Cloneable Interfaces.
·         ArrayList and Vector Classes Implements RandomAccess Interface. So that we can Access any Random Element with the Same Speed.
·         RandomAccess Interface Present in java.utilPackage and it doesn't contain any Methods. Hence it is a Marker Interface.
·         Hence ArrayList is Best Suitable if Our Frequent Operation is Retrieval Operation.

ArrayList l1 = new ArrayList();
LinkedList l2 = new LinkedList();

System.out.println(l1 instanceofSerializable); //true
System.out.println(l2 instanceofCloneable); //true
System.out.println(l1 instanceofRandomAccess); //true
System.out.println(l2 instanceofRandomAccess); //false

Differences between ArrayList and Vector: 

ArrayList
LinkList
Every Method Present Inside ArrayListis Non – Synchronized.
Relatively Performance is High because Threads are Not required to Wait
At a Time Multiple Threads are allow to Operate on ArrayList Simultaneously and Hence ArrayList Object is Not Thread Safe
At a Time Only One Thread is allow to Operate on Vector Object and Hence Vector Object is Always Thread Safe.
Relatively Performance is High because Threads are Not required to Wait
Relatively Performance is Low because Threads are required to Wait.


Que: How to get Synchronized Version of ArrayList Object?
By Default ArrayList Object is Non- Synchronized but we can get Synchronized Version ArrayList Object by using the following Method of Collections Class.
public static List synchronizedList(List l)

example:-

 ArrayListal = new ArrayList ();
 List l = Collections.synchronizedList(al);
 Where :-
 l=> is Synchronized      Version      
 al=> is Non - Synchronized           Version


Similarly we can get Synchronized Version of Set and Map Objects by using the following Methods of Collection Class.  
    public static Set synchronizedSet(Set s)
    public static Map synchronizedMap(Map m)

·         ArrayList is the Best Choice if we want to Perform Retrieval Operation Frequently.
·         But ArrayList is Worst Choice if Our Frequent Operation is Insertion OR Deletion in the Middle. Because it required Several Shift Operations Internally.


LinkedList:
 o   The Underlying Data Structure is Double LinkedList.
o   Insertion Order is Preserved. 
o   Duplicate Objects are allowed.
o   Heterogeneous Objects are allowed.
o   null Insertion is Possible.
o   Implements Serializable and Cloneable Interfaces but Not RandomAccessInterface.
o   Best Choice if Our Frequent Operation is Insertion OR Deletion in the Middle.
o   Worst Choice if Our Frequent Operation is Retrieval.

Constructors:

1) LinkedList l = new LinkedList(); Creates an Empty LinkedList Object.

2) LinkedList l = new LinkedList(Collection c); Creates an Equivalent LinkedList             Object for the given Collection. 

Methods: Usually we can Use LinkedList to Implement Stacks and Queues. To Provide Support for this Requirement LinkedList Class Defines the following 6 Specific Methods.

1) void addFirst(Object o)
2) void addLast(Object o)
3) Object getFirst()
4) Object getLast()
5) Object removeFirst()
6) Object removeLast()
   Example :-

importjava.util.LinkedList;
classLinkedListDemo
public static void main(String[] args)
 {  
LinkedList l = new LinkedList();  
l.add("DashZin");  
l.add(30); 
 l.add(null);  
l.add("DashZin");  
l.set(0, "Software");  
l.add(0,"Info"); 
 l.removeLast();  
l.addFirst("CCC");  
System.out.println(l); //[CCC, Info, Software, 30, null]
 }
 }

Vector:
·         The Underlying Data Structure is Resizable Array ORGrowable Array.  
·         Insertion Order is Preserved.
·         Duplicate Objects are allowed.
·         Heterogeneous Objects are allowed.
·         null Insertion is Possible.
·         Implements Serializable, Cloneable and RandomAccess interfaces.
·         Every Method Present Inside Vector is Synchronized and Hence Vector Object is Thread Safe.
·         Vector is the Best Choice if Our Frequent Operation is Retrieval.
·         Worst Choice if Our Frequent Operation is Insertion OR Deletion in the Middle.

Constructors:

1) Vector v = new Vector();
Creates an Empty Vector Object with Default Initial Capacity 10.
Once Vector Reaches its Max Capacity then a New Vector Object will be Created with 
                   New Capacity =  Current Capacity * 2

2) Vector v = new Vector(intinitialCapacity);

3) Vector v = new Vector(intinitialCapacity, intincrementalCapacity);

             4) Vector v = new Vector(Collection c);

 Example:-
                Import java.util.Vector;
classVectorDemo
 { 
public static void main(String[] args)
 {  
Vector v = new Vector();  
System.out.println(v.capacity()); //10  
for(int i = 1; i<=10; i++) {   
v.addElement(i);  
}  
System.out.println(v.capacity()); //10  
v.addElement("A");  
System.out.println(v.capacity()); //20  
System.out.println(v); //[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, A] 
}
 }




Stack: 

It is the Child Class of Vector.  It is a Specially Designed Class for Last In First Out (LIFO) Order.

Constructor:Stack s = new Stack();

Methods:

1)      Object push(Object o); => To Insert an Object into the Stack.
2)      Object pop(); => To Remove and Return Top of the Stack.
3)      Object peek(); => Ro Return Top of the Stack without Removal.
4)      boolean empty(); => Returns true if Stack is Empty
5)      int search(Object o); =>Returns Offset if the Element is Available Otherwise Returns -1.

importjava.util.Stack;
classStackDemo
public static void main(String[] args)
{  
Stack s = new Stack();  
s.push("A");  
s.push("B");  
s.push("C");  
System.out.println(s); //[A, B, C]  
System.out.println(s.search("A")); //3  
System.out.println(s.search("Z")); //-1 
}
}



Wednesday, 3 January 2018

Cursors In Java

DashZin

  •     If we want to get Objects One by One from the Collection  then  we should go for Cursors.
  •    There are 3 Types of Cursors Available in Java.

  1.               Enumeration 
  2.               Iterator
  3.               ListIterator 
 Enumeration:

· We can Use Enumeration to get Objects One by One from the Collection.
· We can Create Enumeration Object by using elements(). 

        public Enumeration elements();

Eg:-
        Enumeration e = v.elements(); //v is Vector Object.

Methods:
        ·       public booleanhasMoreElements();
        ·       public Object nextElement();

vector v = new vector();
      for(int i=0; i<=10;i++)
      {
            v.addElement(i);
      }
      System.out.println(v); //[0,1,2,3,4,5,6,7,8,9,10]
      Enumeration e=v.elements();
6,8,10
      }
while(e.hasmoreElements())
      {     
            Integer I = (Integer)e.nextElement();
            if(I%2 == 0)
 
      System.out.println(v); //[0,1,2,3,4,5,6,7,8,9,10]



Limitations of Enumeration:
  • Enumeration Concept is Applicable Only for Legacy Classes and it is Not a Universal Cursor.  
  • By using Enumeration we can Perform Read Operation and we can't Perform Remove Operation.
To Overcome Above Limitations we should go for Iterator.

Iterator:
  • We can Use Iterator to get Objects One by One from Collection.
  • We can Apply Iterator Concept for any Collection Object. Hence it is Universal Cursor.
  • By using Iterator we can Able to Perform Both Read and Remove Operations.
  • We can Create Iterator Object by using iterator() of Collection Interface. 
    public Iterator iterator();

Methods:
  •  public booleanhasNext()
  •  public Object next()
  •  public void remove()


import java.util.ArrayList;
import java.util.Iterator;
 
public class IteratorDemo1 {
 
  public static void main(String args[]){
    ArrayList names = new ArrayList();
    names.add("Dashzin");
    names.add("Info");
    names.add("Blog");
 
    Iterator it = names.iterator();
 
    while(it.hasNext()) {
      String obj = (String)it.next();
      System.out.println(obj);
    }
  }
 
}



Limitations:  
  • ·   By using Enumeration and Iterator we can Move Only towards Forward Direction and we can’t Move Backward Direction. That is these are Single Direction Cursors but NotBiDirection.
  • ·   By using Iterator we can Perform Only Read and Remove Operations and we can't Perform Addition of New Objects and Replacing Existing Objects.

To Overcome these Limitations we should go for ListIterator.


ListIterator:

  • ListIterator is the Child Interface of Iterator.
  • By using ListIterator we can Move either to the Forward Direction OR to the Backward Direction. That is it is a Bi-Directional Cursor.
  • By using ListIterator we can Able to Perform Addition of New Objects and Replacing existing Objects. In Addition to Read and Remove Operations.
  • We can Create ListIterator Object by using listIterator().                         
                                 Public ListIterator listIterator();

Eg: ListIteratorltr = l.listIterator(); //l is Any List Object

Method :-

void add(int index,Object element)
It is used to insert element into the invoking list 
at the index passed in the index.
boolean addAll(int index,Collection c)
It is used to insert all elements of c into the 
 invoking list at the index passed in the index.
object get(int index)
It is used to return the object stored at the 
specified index within the invoking collection.
object set(int index,Object element)
It is used to assign element to the location 
specified by index within the invoking list.
object remove(int index)
It is used to remove the element at position 
index from the invoking list and return 
the deleted element.
ListIterator listIterator()
It is used to return an iterator to the start of 
the invoking list.
ListIterator listIterator(int index)
It is used to return an iterator to the invoking 
list that begins at the specified index.


import java.util.*;
classListIteratorDemo { 
public static void main(String[] args) {  
LinkedList l = new LinkedList();  
l.add("Dashzin");  
l.add("Info");  
l.add("Ankit");  
l.add("Naag");  
System.out.println(l);  
ListIteratorltr = l.listIterator();  
while(ltr.hasNext())
{   
String s = (String)ltr.next();   
if(s.equals("Venki"))    
ltr.remove();   
if(s.equals("Naag"))    
ltr.add("Chaitu");   
if(s.equals("Chiru"))    
ltr.add("Charan");  
}  
System.out.println(l); 
}
}



Comparison Table of 3 Cursors: 

Property
Enumeration
Iterator
ListIterator
Applicable For
Only Legacy Classes
Any Collection Objects
Only List Object
Movement
Single Direction (Only Forward)
Single Direction (Only Forward)
Bi-Directional
How To Get
By using elements()
By using iterator()
By using listIterator() of List(I)
Accessability
Only Read
Read and Remove
Read , Remove, Replace And Addition of New Objects
Methods
hasMoreElements(), nextElement()
hasNext(), next(),remove()

9Methods
Is it legacy?
Yes (1.0 Version)
No (1.2 Version)
No (1.2 Version)