Showing posts with label Collection. Show all posts
Showing posts with label Collection. Show all posts

Friday, June 17, 2016

String Tokenizer Class example Java

String Tokenizer Class 

This class is useful to break a string into pieces called Tokens.These tokens are then stored in the StringTokenizer object from where they can retrieved.The code to create an object to String Tokenizer .

StringTokenizer Class Methods

  • int countTokens()
  • boolean hasMoreTokens()
  • String nextToken()
Program:


/**
 * 
 */
package com.collectionpack;

import java.util.StringTokenizer;

/**
 * @author Abhinaw.Tripathi
 *
 */
public class StringTokenizerApp
{
/**
* @param args
*/
public static void main(String[] args)
{
String str="I am an Android Developer";
StringTokenizer st=new StringTokenizer(str," ");
System.out.println("The tokens are: ");
while(st.hasMoreTokens())
{
String one=st.nextToken();
System.out.println(one);
}

}

}

Output:

The tokens are: 
I
am
an
Android
Developer

Using Comparator to Sort an Array example in java

Using Comparator to Sort an Array

It offers an interface , called Comparator that is useful to impose a total ordering on a collection of elements.It can be used to sort the elements of an array into ascending order or descending order.

interface Comparator<T>,where T is generic type

Program Sample:

/**
 * 
 */
package com.collectionpack;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Comparator;

/**
 * @author Abhinaw.Tripathi
 *
 */
class Ascending implements Comparator<Integer>
{

@Override
public int compare(Integer o1, Integer o2)
{

return o1.compareTo(o2);
}

}

class Desending implements Comparator<Integer>
{

@Override
public int compare(Integer o1, Integer o2)
{
return o2.compareTo(o1);
}

}

public class ComparatorApp
{
public static void main(String[] args) throws NumberFormatException, IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("How many elements? ");
int size=Integer.parseInt(br.readLine());

Integer arr[] =new Integer[size];

for(int i=0;i<size;i++)
{
System.out.println("Eneter int: ");
arr[i]=Integer.parseInt(br.readLine());
}

Arrays.sort(arr, new Ascending());
System.out.println("Sorted in asending order");
display(arr);

Arrays.sort(arr,new Desending());
System.out.println("sorted in desending order");
display(arr);
}

private static void display(Integer[] arr)
{
for(Integer i:arr)
System.out.println(i + "\t");

}


}

Output:
How many elements? 
5
Eneter int: 
26
Eneter int: 
89
Eneter int: 
69
Eneter int: 
78
Eneter int: 
456
Sorted in asending order
26
69
78
89
456
sorted in desending order
456
89
78
69
26



Array Class example java

Array Class

Arrays class provides methods to perform certain operations on any one dimensional array.All the methods of the array class are static ,So they can be called in the form of Arrays.methodname() .

Arrays Class Methods

  • static void sort(array)
  • static void sort(array,int start,int end)
  • static int binarySearch(array,element)
  • static boolean equals(array1,array2)
  • static array copyOf(source-array,int n)
  • static void fill(array,value)
Program:


/**
 * 
 */
package com.collectionpack;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

/**
 * @author Abhinaw.Tripathi
 *
 */
public class ArraysDemo 
{

public static void main(String[] args) throws NumberFormatException, IOException
    {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int arr[]=new int[5];
for(int i=0;i<5;i++)
{
System.out.println("Enter an Integer: ");
arr[i]=Integer.parseInt(br.readLine());
}
System.out.println("Contents of the Array");
display(arr);
Arrays.sort(arr);
System.out.println("The sorted array: ");
display(arr);
System.out.println("Which element to search?");
int element=Integer.parseInt(br.readLine());
int index=Arrays.binarySearch(arr, element);
if(index < 0)
System.out.println("Elemnt not found!!!");
else
System.out.println("Element is found at location: " +(index+1));
}

private static void display(int[] arr)
{
for(int i:arr)
System.out.println(i);
}

}

Output:

Enter an Integer: 
2
Enter an Integer: 
1
Enter an Integer: 
3
Enter an Integer: 
45
Enter an Integer: 
52
Contents of the Array
2
1
3
45
52
The sorted array: 
1
2
3
45
52
Which element to search?
3
Element is found at location: 3



Hashtable , HashMap, Set , List differences java

What is difference between HashMap and Hashtable?
Ans:

HashMap= HashMap is not synchronized.In case of single thread, using HashMap is faster than than the Hashtable. HashMap allows null keys and null values to be stored.Iterator in the HashMap is fail-fast.This means Iterator will produce exception if concurrent modifications are made to the HashMap.

Hashtable=Hashtable is synchronized by default.In case of multiple threads,using Hashtable is advisable.With a single thread ,Hashtable becomes slow. Hashtable does not allow null keys or values.Enumeration for the Hashtable is not fail-fast.This means even if concurrent modifications are done to Hashtable ,there will not be any incorrect results produced by Enumeration.

Can you make HashMap synchronized?
Ans:
Yes,we can make it using synchronizedMap() methods as shown:

Collections.synchronizedMap(new HashMap());

What is difference between a Set and a List?
Ans:

Set= A set represent a collection of elements.Order of the element may change in the set.Set will not allow duplicate values to be stored.Accessing elements by their index is not possible. Sets will not allow null elements.

Lists= A List represents ordered collection of elements.List preserves the order of elements in which they are entered.List will allow duplicate values.Accessing elements by index is possible.Lists allow null elements to be stored.

Hashtable Class Java Example

Hashtable Class

Hashtable is similar to HashMap which can store elements in the form of key-value pairs.But Hashtable is synchronized .So in case of multi-threaded environment will get reliable result.

Default Initial Capacity= 11
Load Factor=0.75

Hashtable Class Methods


  • value put(key,value)
  • value get(Object key)
  • Set<K> keySet()
  • Collection<V> values
  • value remove(Object key)
  • void clear()
  • boolean isEmpty()
  • int size()
Program Sample:


/**

 * 
 */
package com.collectionpack;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.Hashtable;

/**
 * @author Abhinaw.Tripathi
 *
 */
public class HashtableDemo
{
/**
* @param args
* @throws IOException 
*/
public static void main(String[] args) throws IOException
{
Hashtable<String, Integer> ht=new Hashtable<>();
ht.put("Ajay", 50);
ht.put("Abhinaw", 100);
ht.put("Kapil", 88);
ht.put("Dhoni", 555);
ht.put("Tendulkar", 80);
System.out.println("The Player Names:");
Enumeration enuum=ht.keys();
while(enuum.hasMoreElements())
{
System.out.println(enuum.nextElement());
}
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Player Name:");
String name=br.readLine();
name=name.trim();
Integer score=ht.get(name);
if(score!=null)
{
int sc=score.intValue();
System.out.println(name + "Scored : " +sc);
}
else
System.out.println("Player not found");
}
}

OutPut:

The Player Names:
Ajay
Tendulkar
Dhoni
Abhinaw
Kapil

Enter Player Name:
Kapil
KapilScored : 88

HashMap Class Java example

Hash Map Class

 HashMap is a collection that stores elements in the form of key-value pairs.If key is provided,its corresponding value can be retrieve easily.Keys should be unique .This means we cannot use duplicate data for keys in the HashMap.
HashMap is not synchronized and hence in case of multi threading we can get unreliable result.

Default Initial Capacity=16
Load Factor=0.75

HashMap Class Methods

  • value put(key,value)
  • value get(Object key)
  • Set<K> keySet()
  • Collection<V> values
  • value remove(Object key)
  • void clear()
  • boolean isEmpty()
  • int size()
Program Sample:


/**
 * 
 */
package com.collectionpack;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

/**
 * @author Abhinaw.Tripathi
 *
 */
public class HashMapDemo {

/**
* @param args
* @throws IOException 
* @throws NumberFormatException 
*/
public static void main(String[] args) throws NumberFormatException, IOException
{
HashMap<String , Long> hm=new HashMap<>();
        String name,str;
        Long phone;
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        while(true)
        {
        System.out.println("1. enter phone entries");
        System.out.println("2. lookup in the phone book");
        System.out.println("3. display name in book");
        System.out.println("4. exit");
       
        System.out.println("your choice: ");
        int n=Integer.parseInt(br.readLine());
        switch (n) 
        {
case 1:
System.out.println("Enter name: ");
name=br.readLine();
System.out.println("Enter phone number: ");
str=br.readLine();
phone=new Long(str);
hm.put(name, phone);
break;
case 2:
System.out.println("Enter name: ");
name=br.readLine();
name=name.trim();
phone=hm.get(name);
System.out.println("Phone :"+phone);
break;
case 3:
Set<String> set=new HashSet<>();
set=hm.keySet();
System.out.println(set);
break;

default:
return;
}
        }
}

}

Output:

1. enter phone entries
2. lookup in the phone book
3. display name in book
4. exit
your choice: 
1
Enter name: 
abhinaw
Enter phone number: 
8130752107
1. enter phone entries
2. lookup in the phone book
3. display name in book
4. exit
your choice: 
2
Enter name: 
abhinaw
Phone :8130752107
1. enter phone entries
2. lookup in the phone book
3. display name in book
4. exit
your choice: 



Vector Class example java

Vector Class

A vector also stores elements similar to ArrayList, but Vector is synchronized.It means if several threads act on same vector object simultaneously,the result will be reliable.

Default Capacity=10
Load Factor=0.75

Vector Class Methods

  • boolean add(element obj)
  • void add(int position,element obj)
  • element remove(int position)
  • boolean remove(Object obj)
  • void clear()
  • element set(int position,Object obj)

  • boolean contains(Object obj)
  • element get(int position)
  • int indexOf(Object obj)
  • int lastIndexOf(Object obj)
  • int size()
  • int capacity()
Program:


/**
 * 
 */
package com.collectionpack;

import java.util.ListIterator;
import java.util.Vector;

/**
 * @author Abhinaw.Tripathi
 *
 */
public class VectorDemo
{

/**
* @param args
*/
public static void main(String[] args)
{
Vector<Integer> vector=new Vector<Integer>();
int x[]={22,10,40,15,60};
for(int i=0;i<x.length;i++)
{
vector.add(x[i]);
}

System.out.println("Vetcor elements:");
for(int  j=0;j<vector.size();j++)
{
System.out.println(vector.get(j));
}
System.out.println("Elements using ListIterator....");
ListIterator lite=vector.listIterator();
System.out.println(("In forward Direction"));
while(lite.hasNext())
{
System.out.println(lite.next() + "\t");
}
System.out.println("In backward direction");
while(lite.hasPrevious())
{
System.out.println(lite.hasPrevious() + "\t");
}
}

}

What is the difference between ArrayList and Vector?
Ans:
ArrayList                                                                                                     Vector

1. ArrayList Object is not Synchronized.    1.Vector Object is synchronized by default.

2. ArrayList is faster in single threaded-       2.In case of Multi-Threads,vector is advisable but           
                                                                           becomes slow in case of single Thread.
-mode.

3.It increases it size by 50% half of its size.  3.It increases its size by doubling it.

Can you synchronize the ArrayList object?

Ans: Yes,we can use synchronizedList() method to synchronize the ArrayList.

          Collections.synchronizedList(new ArrayList());


ArrayList Class Collection example java

ArrayList Class

An ArrayList is like an array, which can grow in memory dynamically.Memory is dynamically allotted and re-allotted to accommodate all the elements. ArrayList is not synchronized. Un-reliable result in case of multi threading.

Default Initial Capacity: 10
Load Factor=0.75

ArrayList Class Methods


  • boolean add(element obj)
  • void add(int position,element obj)
  • element remove(int position)
  • boolean remove(object obj)
  • void clear()
  • element set(int position,element obj)
  • boolean contains(Object obj)
  • element get(int position)
  • int indexOf(Object obj)
  • int lastIndexOf(Object obj)
  • int size()
  • Object[] toArray()

Program:


/**
 * 
 */
package com.collectionpack;

import java.util.ArrayList;
import java.util.Iterator;

/**
 * @author Abhinaw.Tripathi
 *
 */
public class ArrayListDemo {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<String> list=new  ArrayList<>();
list.add("Apple");
list.add("Mango");
list.add("Grapes");
list.add("Guava");
System.out.println("Contents= :" +list);
System.out.println("List size is :" +list.size());
System.out.println("Extracting from the list:");
Iterator it=list.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
}

}

Output:


Contents= :[Apple, Mango, Grapes, Guava]

List size is :4
Extracting from the list:
Apple
Mango
Grapes
Guava



LinkedList Collection Class example java

LinkedList Class

A Linked list contains a group of elements in the form of nodes.Each node will have three fields---the data field contains data and the link fields contain references to previous and next nodes.

Linked List is very convenient to store data.Inserting the elements into the linked list and removing the elements from the linked list is done quickly and takes same amount of time.

LinkedList Class Methods

  • boolean add(element obj)
  • void add(int position,element obj)
  • void addFirst(element obj
  • void addLast(element obj)
  • element removeFirst()
  • element removeLast()
  • element remove(int position)
  • void clear()
  • element get(int position)
  • element getFirst()
  • element getLast()
  • element set(int position,element obj)
  • int size()
  • int indexOf(Object obj)
  • int lastIndexOf(Object obj)
  • Object[] toArray()
Program:


/**
 * 
 */
package com.collectionpack;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;

/**
 * @author Abhinaw.Tripathi
 *
 */
public class LinkedListApp
{
/**
* @param args
* @throws IOException 
* @throws NumberFormatException 
*/
public static void main(String[] args) throws NumberFormatException, IOException
{
LinkedList<String> ll=new LinkedList<>();
ll.add("America");
ll.add("India");
ll.add("japan");
System.out.println("list= "+ll);
int choice = 0;
int position;
String element;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
while(choice < 4)
{
System.out.println("LinkedList  Operation");
System.out.println("1 Add an element");
System.out.println("2 Remove an element");
System.out.println("3 Change an element?");
System.out.println("4 Exist");
System.out.println("Your Choice: ");
choice=Integer.parseInt(br.readLine());
switch (choice) 
{
case 1:
System.out.println("Enter element: ");
element=br.readLine();
position=Integer.parseInt(br.readLine());
ll.add(position - 1,element);
break;
case 2:
System.out.println("Enter position:");
position=Integer.parseInt(br.readLine());
ll.remove(position-1);
break;
case 3:
System.out.println("Eneter element?");
position=Integer.parseInt(br.readLine());
System.out.println("Eneter new element?");
element=br.readLine();
ll.set(position-1, element);
break;
default:
return;
}
}
}

}

Output:

list= [America, India, japan]
LinkedList  Operation
1 Add an element
2 Remove an element
3 Change an element?
4 Exist
Your Choice: 
1
Enter element: 
20


LinkedHashSet Class and Stack Class example java

LinkedHashSet Class

This is a subclass of HashSet class and does not contain any additional members on its own.It is a generic class that has declaration:

class LinkedHashSet<T>

Here.T represents generic type parameter.

LinkedHashSet internally uses a linked list to store the elements.

Stack Class

A stack represents a group of elements stored in LIFO.This means that the element which is stored as a last element into the stack will be the first element to be removed from the stack.

There are three operation can be performed on stack:

  1. Push() ----Inserting an element in stack.
  2. Pop()------Deleting an element from stack.
  3. Peek()-----Searching an element from stack.
Stack Class Methods
  • boolean empty();
  • element peek();
  • element pop();
  • element push(element obj);
  • int search(Object obj);
What is Auto Boxing?
Ans: Converting a primitive data type into an object form automatically is called Auto-Boxing.Auto Boxing is done in generic types.

Program:


/**
 * 
 */
package com.collectionpack;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;

/**
 * @author Abhinaw.Tripathi
 *
 */
public class StackApp
{

/**
* @param args
* @throws IOException 
* @throws NumberFormatException 
*/
public static void main(String[] args) throws NumberFormatException, IOException 
{
Stack<Integer> st=new Stack<>();
int choice = 0;
int position,element;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
while(choice < 4)
{
System.out.println("Stack Operation");
System.out.println("1 Push an element");
System.out.println("2 Pop an element");
System.out.println("3 Search an element?");
System.out.println("4 Exist");
choice=Integer.parseInt(br.readLine());
switch (choice) 
{
case 1:
System.out.println("Enter element: ");
   element=Integer.parseInt(br.readLine());
   st.push(element);
break;
case 2:
Integer obj=st.pop();
System.out.println("Popped= "+ obj);
break;
case 3:
System.out.println("Which element?");
element=Integer.parseInt(br.readLine());
position=st.search(element);
if(position == -1)
System.out.println("Element not found");
else
System.out.println("Position:" +position);
break;
default:
return;
}
System.out.println("stack contents: "+st);
}

}

}

Output:

Stack Operation
1 Push an element
2 Pop an element
3 Search an element?
4 Exist
1
Enter element: 
52
stack contents: [52]
Stack Operation
1 Push an element
2 Pop an element
3 Search an element?
4 Exist



Thursday, June 16, 2016

The Collection Frame Work BeginningJava

Using an Array to Store a Group of Objects

It is possible to store a group of objects into an array.Let us take an example,

Employee arr[]=new Employee[100];
This array can store 100 Employee objects.This can be achieved using a single loop as:

for(int i=0;i<100;i++)
{
  arr[i] =new Employee[data];
}

So,here are few points:

  • Arrays can not grow dynamically.Its size is fixed and at run time its size can not increased or decreased.
  • We can not store different class objects into the same array.The reason is that an array can store only one data type of elements.
  •  Adding the objects at the end of an array is easy but inserting and deleting in middle is difficult.
Collection Objects:

A collection object or a container is an object which can store a group of other objects.A collection object has a class called as Collection Class or Container Class .A group of collection classes are available in the package java.util  and is called Collection Framework.

In fact ,collection object does not store the physical copies of other objects.Since other objects are already available in memory,storing another copy of them into the collection object would be a wasting of Memory.So JVM does not store the copies instead it simply stores the references of other objects into a collection object.

Does a collection object store copies of other objects or their references?
Ans: A collection object stores references of other objects.

All the collection classes in java.util package are the implementation classes of different interfaces as shown:

Interface type                                                                     Implementation classes

Set<T>                                                                                    HashSet,LinkedHashSet

List<T>                                                                                   Stack,LinkedList,ArrayList,Vector

Queue<T>                                                                              LinkedList

Map<K,V>                                                                             LinkedList,HashMap,Hashtable


Sets: A set represents a group of element arranged just like an array.The set will grow dynamically when the elements  are stored into it.A set will not allow duplicate elements.

Lists: Lists are like sets.They store a group of elements.But lists allow duplicate values to be stored.

Queues: A queue represents arrangement of elements in FIFO.This means that an element that is stored as a first element into the queue will be removed first from the queue.

Maps: Maps store elements in the form of key and value pairs.If the key is provided then its corresponding value can be obtained . of curse the keys should have unique values.

Note: In all cases the elements refer to objects only.This means we can not store primitive data type in the collection.

Can you store primitive data type into a collection?
Ans is NO,collections store only objects.

Retrieving Elements  from Collections:
  • Using for-each loop
  • Using Iterator interface
  • Using ListIterator interface
  • Using Enumeration interface
What is the difference between Iterator and ListIterator?
Ans: Both are useful to retrieve elements from a collection.Iterator can retrieve the elements only in forward direction but in ListIterator can retrieve the elements in forward and backward direction also.

What is difference between Enumeration and Iterator?
Ans: Both are useful to get the elements from a collection.Iterator has methods whose names are easy to follow and Enumeration methods are difficult to remember.Also Iterator has an option to remove elements from the collection which is not available in Enumeration.