Hadoop Unit-1 Material
Hadoop Unit-1 Material
Collection Framework
Why Collection Framework?
Variable: Variable is a name which is used to store the value. It holds only one value at a time.
Note:
Declaring more number of variables is not a right practice as the identification of variables is difficult if number of variables
are large.
Arrays:
0 1 2 3 4 5 6 7 ………………99
Limitations of arrays:
Ex1:s[0]=new Student();
Ex2:s[1]=new Student();
Ex3:s[2]=new Customer();
If we execute the above examples, in Ex3 we get compile time error, Incompatible types.
Ready_made methods are not available in arrays. It supports standard data structures.
o[0]=new Student();
o[1]=new Customer();
Collection:
It defines several classes and interfaces which can be used as a group of objects as single entity.
In Java In C++
1.Collection 1.Container
Collection Interface
To represent group of objects as a single entity we are using collection interface.
Collection is the root interface of all classes and interfaces of Collection Framework.
It was introduced from JDK 1.2 version onwards.
Collection interface defines the most common methods which are applicable for any Collection Object.
There are many methods declared in the Collection interface. They are as follows:
2 public booleanaddAll(Collection c) is used to insert the specified collection elements in the invoking
collection.
3 public boolean remove(Object element) is used to delete an element from this collection.
4 public booleanremoveAll(Collection c) is used to delete all the elements of specified collection from the
invoking collection.
5 public booleanretainAll(Collection c) is used to delete all the elements of invoking collection except the
specified collection.
6 public int size() return the total number of elements in the collection.
7 public void clear() removes the total no of element from the collection.
There are only three methods in the Iterator interface. They are:
2 public Object next() It returns the element and moves the cursor pointer to the next element.
3 public void remove() It removes the last elements returned by the iterator. It is rarely used.
Note:
Collection interface doesn’t contain any method to retrieve objects, there is no concrete class which implements collection
class directly.
List Interface
index
0 1 2 3 ………………. 9
Methods in List:
5 intlastIndexOf(Object obj)
Returns the index of the last instance of obj in the invoking list. If obj is not an element of the list, .1 is
returned.
6 ListIterator listIterator( )
Returns an iterator to the start of the invoking list.
Ex:
importjava.util.List;
Import java.util.ArrayList;
Class ExOnList
l.add(20);
l.add(30);
l.add(40);
System.out.println(l,indexOf(20));
L.add(20);
System.out.println(l,indexOf(20));
System.out.println(l.get(4));
System.out.println(l.set(4,50));
System.out.println(l);
ArrayList
Constructor Description
ArrayList(Collection c) It is used to build an array list that is initialized with the elements of the collection
c.
ArrayList(int capacity) It is used to build an array list that has the specified initial capacity.
void add(int index, Object element) It is used to insert the specified element at the specified position index in a list.
booleanaddAll(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.
intlastIndexOf(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.
booleanaddAll(int index, It is used to insert all of the elements in the specified collection into this list,
Collection c) starting at the specified position.
intindexOf(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.
Java ArrayList Example
import java.util.*;
class TestCollection1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Ravi");//Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
//Traversing list through Iterator
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ravi
Vijay
Ravi
Ajay
Constructor Description
LinkedList() It is used to construct an empty list.
LinkedList(Collection c) It is used to construct a list containing the elements of the specified collection, in the
order they are returned by the collection's iterator.
Method Description
void add(int index, Object element) It is used to insert the specified element at the specified position index in a
list.
void addFirst(Object o) It is used to insert the given element at the beginning of a list.
void addLast(Object o) It is used to append the given element to the end of a list.
int size() It is used to return the number of elements in a list
boolean add(Object o) It is used to append the specified element to the end of a list.
boolean contains(Object o) It is used to return true if the list contains a specified element.
boolean remove(Object o) It is used to remove the first occurrence of the specified element in a list.
Object getFirst() It is used to return the first element in a list.
Object getLast() It is used to return the last element in a list.
int indexOf(Object o) It is used to return the index in a list of the first occurrence of the specified element,
or -1 if the list does not contain any element.
int lastIndexOf(Object o) It is used to return the index in a list of the last occurrence of the specified element,
or -1 if the list does not contain any element.
Note: ArrayList and LinkedList both implements List interface and maintains insertion order.
ArrayList LinkedList
1.ArrayList internally uses dynamic array to store elements. 1.LinkedList internally uses doubly linked list to store the
elements.
2.Manipulation with ArrayList is slow because it internally 2.Manipulation with LinkedList is faster than ArrayList
uses array. If any element is removed from the array, all the because it uses doubly linked list so no bit shifting is
bits are shifted in memory. required in memory.
3.ArrayList class can act as a list only because it implements 3.LinkedList can act as a list and queue both because it
List only. implements List and Dequeue interface.
4.ArrayList is better for storing and accessing data. 4.LinkedList is better for manipulating data.
Java Vector
A Vector also stores objects similar to ArrayList, but vector is synchronized. It means even if several threads act
on Vector object simultaneously, the result will be reliable.
Vector implements a dynamic memory.
Vector implements List Interface. Like an ArrayList it also maintains insertion order but it is rarely used in non-
thread environment as it is synchronised and due to which gives poor performance in searching, adding, deleting
and update of its elements.
Insertion order is preserved.
It allows RandomAccess of objects.
It doesn’t allows key,value pairs to store.
Duplicate elements are allowed.
“NULL” values are allowed.
It provides thread safe.
1 Vector( )
This constructor creates a default vector, which has an initial size of 10.
2 Vector(int size)
This constructor accepts an argument that equals to the required size, and creates a vector whose initial capacity is
specified by size.
4 Vector(Collection c)
This constructor creates a vector that contains the elements of collection c.
Apart from the methods inherited from its parent classes, Vector defines the following methods −
2 boolean add(Object o)
Appends the specified element to the end of this Vector.
3 boolean addAll(Collection c)
Appends all of the elements in the specified Collection to the end of this Vector, in the order that they are returned
by the specified Collection's Iterator.
6 int capacity()
Returns the current capacity of this vector.
7 void clear()
Removes all of the elements from this vector.
8 Object clone()
Returns a clone of this vector.
10 boolean containsAll(Collection c)
Returns true if this vector contains all of the elements in the specified Collection.
13 Enumeration elements()
Returns an enumeration of the components of this vector.
15 boolean equals(Object o)
Compares the specified Object with this vector for equality.
16 Object firstElement()
Returns the first component (the item at index 0) of this vector.
18 int hashCode()
Returns the hash code value for this vector.
22 boolean isEmpty()
Tests if this vector has no components.
23 Object lastElement()
Returns the last component of the vector.
27 boolean remove(Object o)
Removes the first occurrence of the specified element in this vector, If the vector does not contain the element, it is
unchanged.
28 boolean removeAll(Collection c)
Removes from this vector all of its elements that are contained in the specified Collection.
29 void removeAllElements()
Removes all components from this vector and sets its size to zero.
33 boolean retainAll(Collection c)
Retains only the elements in this vector that are contained in the specified Collection.
34 Object set(int index, Object element)
Replaces the element at the specified position in this vector with the specified element.
37 int size()
Returns the number of components in this vector.
39 Object[] toArray()
Returns an array containing all of the elements in this vector in the correct order.
40 Object[] toArray(Object[] a)
Returns an array containing all of the elements in this vector in the correct order; the runtime type of the returned
array is that of the specified array.
41 String toString()
Returns a string representation of this vector, containing the String representation of each element.
42 void trimToSize()
Trims the capacity of this vector to be the vector's current size.
Ex:
import java.util.*;
public class PrintElements
{
public static void main(String args[])
{
Vector vect1 = new Vector();
vect1.add("Jyostna");
vect1.add(100);
vect1.add(10.5);
vect1.add(new Date());
Enumeration e = vect1.elements();
System.out.println("Vector Elements:");
while(e.hasMoreElements())
{
System.out.println(e.nextElement());
}
}
1 boolean hasMoreElements( )
When implemented, it must return true while there are still more elements to extract, and false when all the
elements have been enumerated.
2 Object nextElement( )
This returns the next object in the enumeration as a generic Object reference.
ArrayList Vector
1.ArrayList is not synchronized. 1.Vector is synchronized.
2.ArrayList increments 50% of current arraysize if number 2.Vector increments 100% means doubles the array size if
of elements exceeds from its capacity. total number of element exceeds than its capacity.
3.ArrayList is not a legacy class.it was introduced in JDK 3.Vector is a legacy class.
1.2.
4.ArrayList is fast because it is not synchronized. 4.Vector is slow because it is synchronized.
5.ArrayList use Iterator interface to traverse the elements. 5.Vector uses Enumeration interface to traverse the
elements, but it can use iterator also.
Java Stack
Stack is a subclass of Vector that implements a standard last-in, first-out stack.
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.
1 boolean empty()
Tests if this stack is empty. Returns true if the stack is empty, and returns false if the stack contains elements.
2 Object peek( )
Returns the element on the top of the stack, but does not remove it.
3 Object pop( )
Returns the element on the top of the stack, removing it in the process.
import java.util.*;
public class StackDemo {
Set Interface
Set is child interface of Collection interface.It was introduced from JDK 1.2 version onwards.
A set represent group of elements arranged just like an array.
The set will grow dynamically when the elements are stored into it.
A set will not .allow duplicate elements.If we try to pass the same element that is already existed in the Set,then it
is not stored into the Set
1 add( )
Adds an object to the collection.
2 clear( )
Removes all objects from the collection.
3 contains( )
Returns true if a specified object is an element within the collection.
4 isEmpty( )
Returns true if the collection has no elements.
5 iterator( )
Returns an Iterator object for the collection, which may be used to retrieve an object.
6 remove( )
Removes a specified object from the collection.
7 size( )
Returns the number of elements in the collection.
Example
Set has its implementation in various classes like HashSet, TreeSet, LinkedHashSet.Following is an example to
explain Set functionality
import java.util.*;
try {
set.add(count[i]);
System.out.println(set);
System.out.println(sortedSet);
catch(Exception e) {}
It is a child class of HashSet class and it doesn’t contain any additional methods on its own.
It contains unique elements.
It allows NULL values.
It maintains insertion order.
The underline data structure for LinkedHashSet is Doubly linked list.
Constructors of Java LinkedHashSet class
Constructor Description
HashSet() It is used to construct a default HashSet.
HashSet(Collection c) It is used to initialize the hash set by using the elements of the collection c.
LinkedHashSet(int capacity) It is used initialize the capacity of the linkedhashset to the given integer value
capacity.
LinkedHashSet(int capacity, float fillRatio) It is used to initialize both the capacity and the fill ratio (also
called load capacity) of the hash set from its argument.
SortedSet is child interface of Set interface.It was introduced from JDK 1.2 version onwards.
It declares the behaviour od a sorted set in ascending order.
Note:In SortedSet several methods may rise exceptions like:
NoSuchElementException,when an object is not available in the sorted set.
ClassCastException is generated when object is incompatible with SortedSet.
import java.util.NavigableSet;
import java.util.TreeSet;
ns.add(0);
ns.add(1);
ns.add(2);
ns.add(3);
ns.add(4);
ns.add(5);
ns.add(6);
import java.util.NavigableSet;
import java.util.TreeSet;
ns.add(1);
ns.add(2);
ns.add(3);
ns.add(4);
ns.add(5);
ns.add(6);
}
Output:
lower(3): 2
floor(3): 3
higher(3): 4
ceiling(3): 3
pollFirst(): 0
pollLast(): 6
TreeSet class is a child class of NaavigableSetinterface.It was introduced from JDK 1.2 version onwards.
TreeSet is similar to HashSeyt except that it sorts the elements in the ascending order while HashSet doesn’t
maintain any order.
It doesn’t allows Null values.
Access and retrieval time are quite fast which makes TreeSet an excellent choice when storing large amounts of stored
information that must be found very quickly.
Operations on Queue:
Type of Operation Throws Exception Returns Special value
insert add(Object o) offer(Object o)
remove remove() poll()
examine element() peek()
Ex;
import java.util.*;
class ExOnQueue{
public static void main(String[] args){
Queue q=new PriorityQueue();
q.add(10);
q.add(20);
q.add(30);
for(Object o: q)
System.out.println(o);
}
}
Java PriorityQueue class
It is a child class of Queue Interface.It is introduced from JDK 1.5 version on wards.
The underline datastructure for PriorityQueue is PriorityHeap.
The PriorityQueue size is unbounded.We may give initial capacity of PriorityQueue at the time of its creation.
It is not thread safe.
It doesn’t order the objects in FIFO order. Java PriorityQueue Example
import java.util.*;
class TestCollection12{
public static void main(String args[]){
PriorityQueue<String> queue=new PriorityQueue<String>();
queue.add("Amit");
queue.add("Vijay");
queue.add("Karan");
queue.add("Jai");
queue.add("Rahul");
System.out.println("head:"+queue.element());
System.out.println("head:"+queue.peek());
System.out.println("iterating the queue elements:");
Iterator itr=queue.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
queue.remove();
queue.poll();
System.out.println("after removing two elements:");
Iterator<String> itr2=queue.iterator();
while(itr2.hasNext()){
System.out.println(itr2.next());
}
}
}
Output:
head:Amit
head:Amit
iterating the queue elements:
Amit
Jai
Karan
Vijay
Rahul
after removing two elements:
Karan
Rahul
Vijay
Java Comparable interface:
Java Comparable interface is used to order the objects of user-defined class.This interface is found in java.lang package and
contains only one method named compareTo(Object). It provide single sorting sequence only i.e. you can sort the elements
on based on single data member only. For example it may be rollno, name, age or anything else.
compareTo Java Comparable interface (Object obj) method
public int compareTo(Object obj): is used to compare the current object with the specified object.We can sort the elements
of: 1.String objects
Comparable and Comparator both are interfaces and can be used to sort collection elements.
But there are many differences between Comparable and Comparator interfaces that are given below.
Comparable Comparator
1) Comparable provides single sorting sequence. In Comparator provides multiple sorting sequence. In other words,
other words, we can sort the collection on the basis we can sort the collection on the basis of multiple elements such
of single element such as id or name or price etc. as id, name and price etc.
2) Comparable affects the original class i.e. actual Comparator doesn't affect the original class i.e. actual class is
class is modified. not modified.
3) Comparable provides compareTo() method to Comparator provides compare() method to sort elements.
sort elements.
5) We can sort the list elements of Comparable type We can sort the list elements of Comparator type
by Collections.sort(List) method. by Collections.sort(List,Comparator) method.
Map is useful if you have to search, update or delete elements on the basis of key.
Map can't be traversed so you need to convert it into Set using keySet() or entrySet() method.
HashMap - HashMap is the implementation of Map but it doesn't maintain any order.
LinkedHashMap-LinkedHashMap is the implementation of Map, it inherits HashMap class. It maintains insertion order.
TreeMap-TreeMap is the implementation of Map and SortedMap, it maintains ascending order.
Useful methods of Map interface:
Method Description
Object put(Object key, Object value) It is used to insert an entry in this map.
void putAll(Map map) It is used to insert the specified map in this map.
Object remove(Object key) It is used to delete an entry for the specified key.
Object get(Object key) It is used to return the value for the specified key.
boolean containsKey(Object key) It is used to search the specified key from this map.
Set keySet() It is used to return the Set view containing all keys.
Set entrySet() It is used to return the Set view containing all keys and values
Map.Entry Interface
Entry is the sub interface of Map. So we will be accessed it by Map.Entry name. It provides methods to get key and value.
Methods of Map.Entry interface
Method Description
Java HashMap class implements the map interface by using a hashtable. It inherits AbstractMap class and implements Map
interface.
The important points about Java HashMap class are:
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
Hierarchy of HashMap class
As shown in the above figure, HashMap class extends AbstractMap class and implements Map interface.
HashMap class declaration
Let's see the declaration for java.util.HashMap class.
1. public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable
HashMap class Parameters
Let's see the Parameters for java.util.HashMap class.
K: It is the type of keys maintained by this map.
V: It is the type of mapped values.
Constructors of Java HashMap class
Constructor Description
HashMap(Map m) It is used to initializes the hash map by using the elements of the given Map object m.
HashMap(int capacity) It is used to initializes the capacity of the hash map to the given integer value, capacity.
HashMap(int capacity, float It is used to initialize both the capacity and fill ratio of the hash map by using its
fillRatio) arguments.
Methods of Java HashMap class
Method Description
void clear() It is used to remove all of the mappings from this map.
boolean containsKey(Object key) It is used to return true if this map contains a mapping for the
specified key.
boolean containsValue(Object value) It is used to return true if this map maps one or more keys to the
specified value.
Object clone() It is used to return a shallow copy of this HashMap instance: the keys
and values themselves are not cloned.
Set entrySet() It is used to return a collection view of the mappings contained in this
map.
Set keySet() It is used to return a set view of the keys contained in this map.
Object put(Object key, Object value) It is used to associate the specified value with the specified key in
this map.
Collection values() It is used to return a collection view of the values contained in this
map.
Java LinkedHashMap class is Hash table and Linked list implementation of the Map interface, with predictable iteration
order. It inherits HashMap class and implements the Map interface.
The important points about Java LinkedHashMap class are:
o A LinkedHashMap contains values based on the key.
o It contains only unique elements.
o It may have one null key and multiple null values.
o It is same as HashMap instead maintains insertion order.
LinkedHashMap class declaration
Let's see the declaration for java.util.LinkedHashMap class.
1. public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V>
LinkedHashMap class Parameters
Let's see the Parameters for java.util.LinkedHashMap class.
o K: It is the type of keys maintained by this map.
o V: It is the type of mapped values.
Constructors of Java LinkedHashMap class
LinkedHashMap()-It is used to construct a default LinkedHashMap.
LinkedHashMap(int capacity)- It is used to initialize a LinkedHashMap with the given capacity.
LinkedHashMap(int capacity, float fillRatio)- It is used to initialize both the capacity and the fillRatio.
LinkedHashMap(Map m).- It is used to initialize the LinkedHashMap with the elements from the given Map class m.
Methods of Java LinkedHashMap class
Object get(Object key)- It is used to return the value to which this map maps the specified key.
void clear()-It is used to remove all mappings from this map.
boolean containsKey(Object key)- It is used to return true if this map maps one or more keys to the specified value.
Java TreeMap class implements the Map interface by using a tree. It provides an efficient means of storing key/value pairs in
sorted order.
The important points about Java TreeMap class are:
o A TreeMap contains values based on the key. It implements the NavigableMap interface and extends AbstractMap
class.
o It contains only unique elements.
o It cannot have null key but can have multiple null values.
o It is same as HashMap instead maintains ascending order.
TreeMap class declaration
Let's see the declaration for java.util.TreeMap class.
1. public class TreeMap<K,V> extends AbstractMap<K,V> implements NavigableMap<K,V>, Cloneable, Serializable
TreeMap class Parameters
Let's see the Parameters for java.util.TreeMap class.
o K: It is the type of keys maintained by this map.
o V: It is the type of mapped values.
Constructors of Java TreeMap class
TreeMap()-It is used to construct an empty tree map that will be sorted using the natural order of its key.
TreeMap(Comparator comp)- It is used to construct an empty tree-based map that will be sorted using the comparator
comp.
TreeMap(Map m)- It is used to initialize a tree map with the entries from m, which will be sorted using the natural
order of the keys.
TreeMap(SortedMap sm)- It is used to initialize a tree map with the entries from the SortedMap sm, which will be
sorted in the same order as sm.
Methods of Java TreeMap class:
boolean containsKey(Object key)- It is used to return true if this map contains a mapping for the specified key.
boolean containsValue(Object value)- It is used to return true if this map maps one or more keys to the specified value.
Object firstKey()- It is used to return the first (lowest) key currently in this sorted map.
Object get(Object key)- It is used to return the value to which this map maps the specified key.
Object lastKey()- It is used to return the last (highest) key currently in this sorted map.
Object remove(Object key)- It is used to remove the mapping for this key from this TreeMap if present.
void putAll(Map map)- It is used to copy all of the mappings from the specified map to this map.
Set entrySet()- It is used to return a set view of the mappings contained in this map.
int size()- It is used to return the number of key-value mappings in this map.
Collection values()- It is used to return a collection view of the values contained in this map
Java TreeMap Example:
import java.util.*;
class TestCollection15{
public static void main(String args[]){
TreeMap<Integer,String> hm=new TreeMap<Integer,String>();
hm.put(100,"Amit");
hm.put(102,"Ravi");
hm.put(101,"Vijay");
hm.put(103,"Rahul");
for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Java TreeMap Example: remove()
import java.util.*;
public class TreeMapExample {
public static void main(String args[]) {
// Create and populate tree map
Map<Integer, String> map = new TreeMap<Integer, String>();
map.put(102,"Let us C");
map.put(103, "Operating System");
map.put(101, "Data Communication and Networking");
System.out.println("Values before remove: "+ map);
// Remove value for key 102
map.remove(102);
System.out.println("Values after remove: "+ map);
}
}
Generics
A class that can refer to any type is known as generic class.
Generic classes was added in JDK 1.5 version to provide “compile-time type checking” and removing the risk of
“ClassCastException” that was common while working with collection classes.
Advantages of Java Generics:
1.Type-safety:We can hold a single type of objects in generics.It doesnot allow to store other objects.
2.Type casting is not required:There is no need to typecast the objects.Before generics,we need to type cast.
Ex:
Class ExOnGenerics{
Public static void main(String[] args){
List<Integer> l=new ArrayList<Integer>();
l.add(10);
l.add(20);
l.add(30);
for(Integer i:l)
{
System.out.println(i);
}
}
}
Note:
At the time of list creation,we have specified that the type of elements in the list will be integer.So if we try to add any other
type of object in the list,the program will throw compile time error.Also notice that in for loop we don’t need type casting of
the element in the list,hence removing the ClassCastException at run time.
Ex2:
import java.util.*;
class GenericDemo{
public static void main(String[] args){
Map<Integer,Sring> map=new HashMap<Integer,String>();
map.put(1,”ABC”);
map.put(2,”XYZ”);
map.out(3,”PQR”);
Set <Map.Entry<Integer,String>> set=map.entrySet();
Iterator <Map.Entry<Integer,String>> i=set.iterator();
While(i.hasNext())
{
Map.Entry e=i.next();
System.out.println(e.getKey()+” “+e.getValue());
}
}
}
Generic class:
A class that can refer to any type is known as generic class.Here we are using “T” type parameter to create the generic class
of specific type.
Creating Generic Class:
Class GenDemo<T>{
T obj;
Void add(T obj){
This.obj=obj;
T get(){
return obj;
}
The T type indicates that it can refer to any type(like string,Integer,Employee etc).
The type you specify for the class ,will be used to store and retrieve the data.
Ex:
Public class Box<T>{
Private T t;
Public void add(T t)
{
This.t=t;
}
Public T get(){
Return T;
}
Public static void main(String[] args){
Box<Integer> ibox=new Box<Integer>();
Box<String> sbox=new Box<String>();
ibox.add(new Integer(10));
sbox.add(new String(“JNTUK”));
System.out.println(ibox,get());
System.out.println(sbox.get());
}
}
Type Parameters:
The type parameters naming conversion are important to learn generics thoroughly.The common type parameters are as
follows:
1.T-Type
2.E-Element
3.K-Key
4.N-Number
5.V-Value
Generic Method:
Like generc class,we can create generic method that can accept any type of argument.
Example of java generic method to print array elements,we are using here E to denote the element.
Ex:
Class Gen<T>
{
T ob;
Gen(T ob){
This.ob=ob;
}
Public void show()
{
System.out.println(“The type of Ob”+Ob.getClass.getName());
}
Public T getOb()’{
return ob;
}
}
Class GenTest{
Public static void main(Strig[] args)
{
Gen<String> g1=new Gen<String>(“durga”);
g1.show();
System.out.println(g1.getob());
}
}
The above program is an example of generic classes.
Ex on Generic method:
Public class GenDemo{
Public static <E> void printArray(E[] elements)
{
for(E element : elements){
system.out.println(element);
}
System.out.println();
}
Public static void main(String[] args)
{
Integer[] intArray={10,20,30,40,50};
Character charArray={‘J’,’N’,’T’,’U’,’K’};
System.out.println(“Printing Integer Array”);
printArray(intArray);
Systemout.println(“Printing character array”);
printArray(charArray);
}
}
Wildcard in Java Generics:
The ?(question mark) symbol represents wildcard elements.It means any type.
If we write <? Extends number>,it means any child class of number.
Ex:
Integer,float,double,etc.Now we can call the method of Number class through any child class object.
Import java.util.*;
abstract class Shape{
abstract void draw();
}
class Rectangle extends Shape{
void draw()
{
Systemout.println(“Drawing Rectangle”);
}
}
class Circle extends Shape{
void draw(){
System.out.println(“Drawing Circle”);
}
}
class GenDemo{
public static void drawShapes(List <? Extends Shape> list){
for(Shape s : list){
s.draw();
}
}
public static void main(String[] args){
List<Rectangle> l1=new ArrayList<Rectangle>();
l1.add(new Rectangle());
List<Circle> l2=new ArrayList<Circle>();
l2.add(new Circle());
drawShapes(l1);
drawshapes(l2);
}
}
Wrapper Classes
The main objectives of wrapper classes are:
1.To wrap primitive type into Object form so that we can handle primitives also just like Objects.
Ex:Before JDK 1.5version there is no concept of wrapper class.Upto JDK 1.4 version If we try to add primitives directly to
the collection we get compilation error.
2.To define several utility methods which are required for the primitive.
Ex:String s=Integer.toString(10);
1.Integer:
Note:
Almost all wrapper classes contains 2 constructors,one can take corresponding primitive as argument and the other can take
string as argument.
2.Double:
Note:If the string argument not representing a number then we will get an RuntimeException sayng
NumberFormartException.
3.Char:
4.Float:
5.Long:
Serialisation
Dese
Java Object Network
supporting
form
Deserialisation
Ex on Serialisation:
Class Student implement Serializable{
Public static void main(String [] args){
Student s=new Student();
FileOutputStream fos=new FileOutputStream(“ABC.txt”);
ObjectOutputStream oos=new ObjectOutputStream(fos);
Oos.writeObject(s);
}
}
Fig:Serialisation process
Ex on deserialisation:
Class Student implement Serializable{
Public static void main(String [] args){
Student s=new Student();
FileInputStream fis=new FileInputStream(“ABC.txt”);
ObjectInputStream ois=new ObjectInputStream(fis);
Object o=ois.readObject(s);
Syste.out.println(o);
}
}
Fig:Deserialisation Process
Java Transient Keyword:
Java transient keyword is used in serialization. If you define any data member as transient, it will not be serialized.
Let's take an example, I have declared a class as Student, it has three data members id, name and age. If you serialize the
object, all the values will be serialized but I don't want to serialize one value, e.g. age then we can declare the age data
member as transient.
In this example, we have created the two classes Student and PersistExample. The age data member of the Student class is
declared as transient, its value will not be serialized.
If you deserialize the object, you will get the default value for transient variable.
import java.io.Serializable;
public class Student implements Serializable{
int id;
String name;
transient int age;//Now it will not be serialized
public Student(int id, String name,int age) {
this.id = id;
this.name = name;
this.age=age;
}
public static void main(String args[])throws Exception{
Student s1 =new Student(211,"ravi",22);//creating object
//writing object into file
FileOutputStream f=new FileOutputStream("f.txt");
ObjectOutputStream out=new ObjectOutputStream(f);
out.writeObject(s1);
out.flush();
out.close();
f.close();
System.out.println("success");
}
}