Java Util Package / Collections - Java

ArrayList: ArrayList supports dynamic arrays that can grow or shrink as needed.
It is widely use class to handle the array of data. This class implements List interface.

 

WRITE A PROGRAM ON ARRYS LIST.

import java.util.*;
class Sample
{
public static void main(String args[])
{
ArrayList <String>a1=new ArrayList<String>();
System.out.println("Size of a1: "+a1.size());
a1.add("c");
a1.add("b");
a1.add("k");
a1.add("p");
a1.add(1,"c");
System.out.println("Size: "+a1.size());
System.out.println("Contents: "+a1);
a1.remove(3);
a1.remove("p");
System.out.println(a1);

    for(String k:a1)
System.out.println(k);
System.out.println("Print the Array List uising Index");
for(int i=0;i<a1.size();i++)
System.out.println(a1.get(i));

}
}

List Interface:
List interface  extends Collections, elements can be inserted and deleted using List Interface. This interface instantiate a concreate implementation by using following classes.
ArrayList,LinkedList,Vector,Stack
Ex:
List k=new ArrayList();
List k=new LinkedList();
List k=new Vector()
List k=new Stack();

Program on List Interface

package test;
import java.util.*;
public class listinterface {

            public static void main(String[] args) {
// TODO Auto-generated method stub
List <String>x=new ArrayList<String>(); 
// ArrayList implements List interface so we can use in polymorphisam
x.add("prasad");
x.add("Jyothi");
x.add("geetha");
x.add("Ranesh");

for (String i:x)
System.out.println(i);
}

}

Iterator & ListIterator

Iterator enables you to cycle through a collection, obtaining or removing elements. ListIterator extends Iterator to allow bidirectional traversal of a list using hasPrevious() method, and the modification of elements. This interface instantiate using concreate implementation by using the follwing classes.
ArrayList(),Vector(),LinkedList() .

It has three methods to read the data from the collections.
iterator() ,hasNext() and next() methods

WRITE A PROGRAM ON ITERATOR.

import java.util.*;
class Sample
{
public static void main(String args[])
{
ArrayList <String>hs=new ArrayList<String>();
hs.add("B");
hs.add("A");
hs.add("C");
hs.add("F");
System.out.println(hs);
Iterator li=hs.iterator();
while(li.hasNext())
{
String e=(String)li.next();
System.out.println(e);
// or
// System.out.println(li.next()); 
/*or
Object e=li.next();
System.out.println(e);  */
}
li.remove(); // Delete the last element in arrayList
// Using Iterator we can’t add new value to an ArrayList.

                ListIterator lst=hs.listIterator();
lst.add(“sushma“); // using list iterator we can add and remove values from the ArrayList
while(lst.hasNext())
{
System.out.println(lst.next());
}
while(lst.hasPrevious())
{
Object e=lst.previous();
System.out.println(e);
}
}
}

 

Vector: Vector implements a dynamic array . it is similar to ArrayList class , but with two deferencess . Vector is synchronized , and it contains many legacy methods that are not part of the collections framework, with the release of java2 , Vector was reengineered to extend AbstractList and implemented the List interface,

ArrayList class is best for non-threading environment , Vector is best for threading environment.
Differences between ArrayList and Vector


ArrayList

Vector

1) ArrayList is not synchronized.

Vector is synchronized.

3) ArrayList is not a legacy class, it is introduced in JDK 1.2.

Vector is a legacy class.

4) ArrayList is fast because it is non-synchronized.

Vector is slow because it is synchronized i.e. in multithreading environment, it will hold the other threads in runnable or non-runnable state until current thread releases the lock of object.

5) ArrayList uses Iterator interface to traverse the elements.

Vector uses Enumeration interface to traverse the elements. But it can use Iterator also.

 

Vector()
Vector(size)
Vector(size,incr)
Vector(Collection c)

 

PROGRAM ON VECTOR CLASS

import java.util.*;
class Sample
{
public static void main(String args[])
{
Vector <Integer>v=new Vector<Integer>(3,2);
System.out.println("Size"+v.size());
System.out.println("Capacity"+v.capacity());
v.addElement(new Integer(1));
v.addElement(new Integer(2));
v.addElement(new Integer(3));
v.addElement(new Integer(4));
v.add(20); //we can use add method also

System.out.println("Capacity"+v.capacity());
System.out.println("First"+v.firstElement());
System.out.println("Last"+v.lastElement());
Enumeration x=v.elements();
while(x.hasMoreElements())
{
System.out.println(x.nextElement());

}
}
}

Enumeration: It is an interface to retrieve the values in forward direction  from the Collection classes like Vector,Strack,HashTable etc. it is similar to Iterator interface.
Adition and remove of elements are not allowed,It is synchronized.

Methods: elements(),HasMoreElements(),nextElement()

Ex : Explain the: Above Program
HashMap
HashMap maintains key and value pairs it is similar to HashTable. HashMap Implements Map interface. And AbstractMap classs

Syntax:
            HashMap<K,V> object=new HashMap<K,V>();


Program on HashMap

package test;
import java.util.*;
public class Hash {

            public static void main(String[] args) {

HashMap <Integer,String>k=new HashMap<Integer,String>();
k.put(1,"java");
k.put(2, "Python");
k.put(3, "perl");
k.put(4,"lisp");
k.put(5, "ruby");
//HashpMap Allows Null keys and Null Values
k.put(null,"abcdef");  
k.put(null, "this is nill");
k.put(9, null);
System.out.println(k.get(3)); // read the value of specific index
for (String s:k.values())
System.out.println(s);
System.out.println("Print the values using Key");
for(int i=1;i<=5;i++)
System.out.println(k.get(i));
// using set interface we can read the values from HashMap
Set st=k.entrySet();
Iterator ir=st.iterator();
while(ir.hasNext())
{
System.out.println(ir.next()); // reads index and value
}

ir=st.iterator();
// reading key and value seperately we need to use Map interface this interface contains getKey() and getValue() methods
while(ir.hasNext())
{
Map.Entry<Integer, String> mp=(Map.Entry<Integer, String>) ir.next();
System.out.println("Key "+mp.getKey()+" VAlue "+mp.getValue());

}

                       
}

}

HashTable  : HashTable was the part of original java.util and is a concrete implementaion of a dictionary however java 2 reengineered hashtable so that it also implements the map interface , thus hashtable is now integrated into the collection framework it is similar to hashmap but it is synchronized .
HastTable store key/value pairs in a hash table. when using a HashTable , you specify an object that is used as a key, and the value that you want linked to that key. the key is then hashed , and the resulting hash code is used as the index at which the value is stored within the tbale.
HashTable()
HashTable(int size)
HashTable(int size,float fillratio)
HashTable(Map m)

Difference between HashMap and HashTable / HashMap vs HashTable 

1. Synchronization or Thread Safe :  This is the most important difference between two . HashMap is non synchronized and not thread safe.On the other hand, HashTable is thread safe and synchronized.

When to use HashMap ?  answer is if your application do not require any multi-threading task, in other words hashmap is better for non-threading applications. HashTable should be used in multithreading applications.

2. Null keys and null values :  Hashmap allows one null key and any number of null values, while Hashtable do not allow null keys and null values in the HashTable object.

3. Iterating the values:  Hashmap object values are iterated by using iterator .HashTable is the only class other than vector which uses enumerator to iterate the values of HashTable object.

4. Performance :  Hashmap is much faster and uses less memory than Hashtable because HashMap is unsynchronized . Unsynchronized objects are often much better in performance in compare to synchronized  object like Hashtable in single threaded environment.

PROGRAM ON HASHTABLE

import java.util.*;
class Sample
{
public static void main(String argc[])
{
Hashtable <String,Double>hash=new Hashtable<String,Double>();
Enumeration names;
String s;
double bal;
hash.put("Bvnr",new Double(122.32));
hash.put("Narayana",new Double(312.32));
hash.put("swapna",new Double(2112.32));
hash.put("soujanya",new Double(1332.32));
hash.put("Govardhan",new Double(1200.32));
names=hash.keys();
while(names.hasMoreElements())
{
s=(String)names.nextElement();
System.out.println(s+":"+hash.get(s));
}
}
}


HashSet:   HashSet class creates a collection that uses a hash table of storage. A hash table stores information by using a mechanisam  called hashing . In hashing the information content of a key is used to determine a unique value, called it’s hash code. The hash code is then used as the index at which the data associated with the key is stored. Which implements set interface.

WRITE A PROGRAM ON HAHSET CLASS.

import java.util.*;
class Sample
{
public static void main(String args[])
{
HashSet <String>hs=new HashSet<String>();
hs.add("B");
hs.add("A");
hs.add("C");
hs.add("P");
hs.add("F");
System.out.println(hs);
}
}

Set Interface

A Set is a Collection that cannot contain duplicate elements. The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited.
We can add and remove the data from the HashSet and treeset data.

import java.util.*;

public class SetDemo
{

  public static void main(String args[]) {
int count[] = {34, 22,10,60,30,22};
Set<Integer> set = new HashSet<Integer>();
try{
for(int i = 0; i<5; i++){
set.add(count[i]);
}
System.out.println(set);

TreeSet sortedSet = new TreeSet<Integer>(set);
System.out.println("The sorted list is:");
System.out.println(sortedSet);

        System.out.println("The First element of the set is: "+
(Integer)sortedSet.first());
System.out.println("The last element of the set is: "+
(Integer)sortedSet.last());
}
catch(Exception e){}
}
}

 

TreeSet  : TreeSet class provides an implement of the set interface that uses a tree of storage. Objects are stored in sortedm ascending order, acces and retrieval times are quite fast whch makes treeset an excellent choice when storing large amounts of sorted information that must be found quickly.

WRITE A PROGRAM ON TREESET CLASS.

import java.util.*;
class Sample
{
public static void main(String args[])
{
TreeSet <String>ts=new TreeSet<String>();
ts.add("B");
ts.add("A");
ts.add("C");
System.out.println(ts);
}
}

 

Linked List

Java LinkedList class uses doubly linked list to store the elements. It extends the AbstractList class and implements List and Deque interfaces.

WRITE A PROGRAM ON LINKED LIST CLASS.

import java.util.*;
class Sample
{
public static void main(String args[])
{
LinkedList <String>l1=new LinkedList<String>();
l1.add("f1");
l1.add("B");
l1.add("E");
l1.add("C");
l1.add("A");
l1.add(1,"A2");
System.out.println(l1);
l1.remove("f");
l1.remove(2);
l1.removeFirst();
l1.removeLast();
System.out.println(l1);
}
}

Stack
Stack is a subclass of Vector which follows Last in and First Out.(LIFO) Order.
Stack only defines the default constructor, which creates an empty stack. Stack includes all the methods defined by Vector, and adds several of its own.
Push() and Pop() are the main methods in stack class


WRITE A PROGRAM ON STACK CLASS.

import java.util.*;
class Sample
{
static void abc(Stack <Integer>st,int a)
{
st.push(new Integer(a));
System.out.println("Stack: "+st);
}
static void pop(Stack <Integer>st)
{
System.out.println("pop->");
Integer a=st.pop();
System.out.println(a);
System.out.println(st);
}
public static void main(String args[])
{
Stack <Integer>st=new Stack<Integer> ();
System.out.println("Stack"+st);
abc(st,42);
abc(st,52);
abc(st,62);
pop(st);
pop(st);
pop(st);

                try
{
pop(st);
}
catch(EmptyStackException e)
{
System.out.println("empty stack");
}
}
}

StringTokenizer : StringTokenizer class provides the first step in this parsing process, often called the lexer (lexical analyzer) or scanner, StringTokenizer implements the enumeration interface. Therefore given asn inout string you can enumerate the individual tokens contained in it using stringtokenizer.
StringTokenizer(Sting st)
StringTolenizer(String st,String delimiters)
StringTokenizer(String st,String delimiter,boolean val);

WRITE A PROGRAM ON STRINGTOKENIZER

import java.util.*;
class Sample
{
String k=”Welcome to vision compuers; company=vision; area=vuyyuru”;
public static void main(String args[])
{         
StringTokenizer st=new StringTokenizer(k,”=;”);
while(st.hasMoreTokens())
{
System.out.println(st.nextToken());
}
}
}

WRITE A PROGRAM ON DATE OBJECT.

import java.util.*;
class Sample
{
public static void main(String args[])
{
Date d=new Date();
System.out.println(d);
long s=d.getTime();
System.out.println(s);
}
}

WRITE A PROGRAM ON CALENDER METHODS

import java.util.*;
class Sample
{
public static void main(String args[])
{
Calendar c=Calendar.getInstance();
System.out.print("Date: ");
System.out.print(" "+c.get(Calendar.DATE)+" ");
System.out.print(c.get(Calendar.YEAR));

                System.out.print("Time:");
System.out.print(c.get(Calendar.MINUTE));
System.out.println(c.get(Calendar.SECOND));
c.set(Calendar.HOUR,10);
c.set(Calendar.MINUTE,20);
c.set(Calendar.SECOND,30);

                System.out.print("Updated time:");
System.out.print(c.get(Calendar.HOUR));
System.out.print(c.get(Calendar.MINUTE));
System.out.println(c.get(Calendar.SECOND));
}
}

WRITE A PROGRAM ON RANDOM CLASS.

import java.util.*;
class Sample
{
public static void main(String args[])
{
Random r=new Random();
double val;
double sum=0;
for(int i=0;i<10;i++)
{
val=r.nextGaussian();
sum+=val;
System.out.println(val);
}
}
}

 

For
Online Classes

Contact Us: 9885348743