For all those who have been searching for a simple and quick reference to learn programming languages and latest technologies in the most easiest format which covers whole of the syllabus.
Friday, June 30, 2017
Friday, June 23, 2017
Thursday, June 22, 2017
Java-Collections
Collection Framework
--------------------
Framework
---------
A framework is collection of interfaces,classes and enum.
Arrays
------
Collection of homogenous elements.
Arrays are type safe.
Performance is good.
Arrays holds both primitives and objects.
Limitations
-----------
i)Arrays are static in nature i,e fixed in size i,e they are not automatically growable and shrinkable.
ii)Arrays are not heterogenous.
iii)No predefined method support to work with arrays.
Collection
----------
A collection is representing group of objects as a single entity.
A collection stores only objects.
Collection allows heterogenous elements.
Collection is dynamic i,e automatically growable and shrinkable.
Collection provides predefined method support.
Limitations
-----------
Collection is not type safe.
Performance is low because of convertions internally from primitive to object and object to primitive.
if we want work with built-in datastructures Collection framework provides classes and interfaces to work with datastructres.
Collection framework is used to process data while performing database operations in java project,it is also to process huge data in general appliactions(Non-database applications).
Collection interface
--------------------
A Collection is root interface of all collections.
Collection interface consists of methods which are common for the entire Collections.
All Collections are available in java.util.*
Methods summary of Collection interface
---------------------------------------
public abstract int size();
returns size of collection
public abstract boolean isEmpty();
returns true if collection is empty otherwise false.
public abstract boolean contains(java.lang.Object);
checks whether an object is available in a collcetion or not returns true if it available otherwise false.
public abstract java.util.Iterator<E> iterator();
This method returns iterator object.
public abstract java.lang.Object[] toArray();
convert collection to Array.
public abstract boolean add(java.lang.Object);
adds an objectto collection.
public abstract boolean remove(java.lang.Object);
remove an object from collection.
public abstract boolean containsAll(java.util.Collection<?>);
checks whether a Collection is available in another collection or not returns true if it available otherwise false.
public abstract boolean addAll(java.util.Collection<? extends E>);
This is used to add a Collection to another collection.
public abstract boolean removeAll(java.util.Collection<?>);
This is used to remove a collection object from a another collection.
public abstract boolean retainAll(java.util.Collection<?>);
public abstract void clear();
clears collections.
public abstract boolean equals(java.lang.Object);
Used to check whether 2 objects are same or not returns true if both the objects are same otherwise false.
public abstract int hashCode();
returns hashCode of a collection.
List
----
It is child interface of collection.
Properties
----------
List is dynamic i,e it is growable and shrinkable.
List is heterogenous.
List allows duplicate values.
List preserves insertion order.
List allows null values.
Implementation classes of List
------------------------------
A List is implemented in the following classes.
i)ArrayList
ii)LinkedList
iii)Vector
iv)Stack
Collection
^
|
List
| | |
ArrayList LinkedList Vector
|
Stack
Methods of List interface
-------------------------
public abstract Object get(int);
It is used to get an object from List.
public abstract Object set(int, Object);
used to set or update an object in a List
public abstract void add(int, Object);
Adds an object at a given index.
public abstract Object remove(int);
remove an object at a given index.
public abstract int indexOf(java.lang.Object);
returns index of an object.
ArrayList
---------
It is implementation class of List interface
The underlying datastructure of ArrayList is dynamic array.
Constructors
------------
public java.util.ArrayList(int);
creates an ArrayList with customized capacity.
public java.util.ArrayList();
creates an ArrayList with default capacity.
public java.util.ArrayList(java.util.Collection<? extends E>
This is used to copy any collection to ArrayList.
The default capacity of ArrayList is 10.
ArrayList is introduced in 1.2 version.
ArrayList also implements the following interfaces
i)RandonAccess.
ii)Serializable.
iii)Cloneable.
RandomAccess
------------
This interface makes ArrayList efficient in performing retrieval operation.
Serializable
------------
If we implement Serializable interface then we can write an object to a file or we can send an object through a network.
Cloneable
---------
This allows us to create an exact copy of an object which we call this as cloning.
The above 3 interfaces are called marker interfaces.
Marker interface
----------------
A marker interface is an interface without any methods.
A marker interface provides additional capability to objects.
public interface RandomAccess
{
}
Program to demonstrate ArrayList
--------------------------------
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList list=new ArrayList();
list.add(10);
list.add(20.5);
list.add("Manohar");
list.add(true);
list.add(null);
list.add(10);
System.out.println(list);
}
Program
-------
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList list = new ArrayList();
list.add(10);
list.add(20.5);
list.add("Manohar");
list.add("JavaBali");
list.add(true);
list.add(null);
list.add(10);
System.out.println(list);
System.out.println("The size is " + list.size());
System.out.println("Is empty " + list.isEmpty());
System.out.println("contains " + list.contains("Manohar"));
//object based removal
System.out.println(list.remove(new Integer(10)));
System.out.println(list);
//index based removal
System.out.println(list.remove(4));
System.out.println(list);
//get
Object obj=list.get(3);
System.out.println(obj);
System.out.println(list.get(4));
//set
list.set(3,"Bull");
System.out.println(list);
list.add(2,"Bahubali");
System.out.println(list);
}
}
}
Program
-------
package com.manohar.java;
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList l=new ArrayList();
l.add(10);
l.add(20);
l.add(30);
l.add(40);
l.add(50);
//displaying size
System.out.println(l.size());//5
//adding object at a given index
l.add(3,35);
System.out.println(l);
//displaying size
System.out.println(l.size());//6
//remove based on index
l.remove(4);
System.out.println(l);
//displaying size
System.out.println(l.size());//5
//remove based on object
l.remove(new Integer(20));
System.out.println(l);
//displaying size
System.out.println(l.size());//5
//contains
System.out.println(l.contains(new Integer(50)));
//toArray
Object obj[]=l.toArray();
for(int i=0;i<obj.length;i++){
System.out.println(obj[i]);
}
//get()
System.out.println("get "+l.get(2));
//set
l.set(2,new Integer(70));
System.out.println(l);
//indexof
System.out.println(l.indexOf(30));
//lastindexof
System.out.println(l.lastIndexOf(70));
//isEmpty
System.out.println(l.isEmpty());
//retains
l.clear();
System.out.println(l);
}
}
i)add() method is represented in 2 forms
add(Object)-->This method will add an object sequentially in a collection.
add(int,object)-->This method add an element at a given index,here the object in the existing location is moved to next location from current location.
set(int,object)->it replaces old element with new element.
remove(Object)-->this method removes an object from a List directly.
remove(int)-->this removes an object based on index,here we should pass int as a value,if the size exceeds it leads to an exception
IndexOutOfBoundsException
case1
-----
package com.manohar.java;
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList l = new ArrayList();
l.add(10);
l.add(20);
l.add(30);
l.add(40);
l.add(50);
for(int i=0;i<l.size();i++)
{
System.out.println(obj);
}
}
}
case2
-----
package com.manohar.java;
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList l = new ArrayList();
l.add(10);
l.add(20);
l.add(30);
l.add(40);
l.add(50);
for(int i=0;i<l.size();i++)
{
Object obj = l.get(i);
System.out.println(obj);
}
}
}
case3
-----
package com.manohar.java;
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList l = new ArrayList();
l.add(10);
l.add(20);
l.add(30);
l.add(40);
l.add(50);
for(int i=0;i<l.size();i++)
{
Object obj = l.get(i);
Integer integer=(Integer)obj;
System.out.println(integer);
}
}
}
case4
-----
package com.manohar.java;
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList l = new ArrayList();
l.add(10);
l.add(20);
l.add(30);
l.add(40);
l.add(50);
for(int i=0;i<l.size();i++)
{
Object obj = l.get(i);
Integer integer=(Integer)obj;
int x=integer.intValue();
int y=integer;
System.out.println(x);
System.out.println(y);
}
}
}
case5
-----
package com.manohar.java;
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList l = new ArrayList();
l.add(10);
l.add(20);
l.add(30);
l.add(40);
l.add(50);
for(int i=0;i<l.size();i++)
{
int val=(int)l.get(i);
System.out.println(val);
}
}
}
Program
-------
package com.manohar.java;
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList l = new ArrayList();
l.add(10);
l.add(11);
l.add(20);
l.add(21);
l.add(30);
l.add(40);
l.add(50);
for (int i = 0; i < l.size(); i++) {
int val = (int) l.get(i);
if (val % 2 == 0) {
System.out.println(val);
}
}
}
}
case7
-----
We can apply casting for related objects otherwise it leads to ClassCastException.
package com.manohar.java;
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String[] args) {
Object obj=10.6;
int val=(int)obj;
System.out.println(val);
}
}
Output
------
Exception in thread "main" java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.Integer
Program
-------
package com.manohar.java;
import java.util.ArrayList;
import java.util.Scanner;
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList l = new ArrayList();
l.add(10);
l.add(11);
l.add(20);
l.add(21);
l.add(30);
l.add(40);
l.add(50);
System.out.println("enter val");
int val=new Scanner(System.in).nextInt();
boolean b=l.contains(val);
if(b){
int index=l.indexOf(val);
System.out.println(index);
System.out.println(l.get(index));
}
else{
System.out.println("element not found");
}
}
}
tostring()
equals()
hashCode()
toString()
----------
toString() is used to convert an object to a String object.
toString method is available in Object class.
whenever we print reference of object the hashcode of an object is displayed in hexadecimal form.
package com.manohar.java;
class Test
{
}
public class ArrayListDemo {
public static void main(String[] args) {
Test t=new Test();
System.out.println(t);//line1
}
}
output
------
com.manohar.java.Test@15db9742
Here the hashcode is represented in hexa form as
packagename.classname@hexacode.
In the above at line we are printing reference of Test class.
Whenever we print reference of an object the print statement internally calls toString() of object which returns hashcode.
we can override toString() method and display userdefined hascode as per program requirement.
Program
-------
package com.manohar.java;
class Test
{
public String toString()
{
Integer val=(int) (Math.random()*1000);
return val.toString();
//return (int)(Math.random()*100000)+"";
}
}
public class ArrayListDemo {
public static void main(String[] args) {
Test t=new Test();
System.out.println(t);
}
}
random() generates a random value from 0.1 to 0.9.
output
------
78890
hashCode()
----------
A hashCode() method returns integer representation of a hashcode().
It is available in object class.
package com.manohar.java;
class Test {
}
public class ArrayListDemo {
public static void main(String[] args) {
Test t = new Test();
System.out.println(t.hashCode());
}
}
output
------
366712642
toString() method of object class calls hashCode() internally and this is converted to String form and returned by toString() method.
A developer also can override hashCode() method and call it from toString().
Program
-------
package com.manohar.java;
class Test {
public int hashCode(){
double val=Math.random()*1000000;
return (int)val;
}
public String toString()
{
return Integer.toHexString(hashCode())+"";
}
}
public class ArrayListDemo {
public static void main(String[] args) {
Test t = new Test();
System.out.println(t);
}
}
output
------
c6ed0
we can convert a hashcode into hexa\octal\binary by using methods in wrapper class.They are
toHexString()-->converts a number to hexa decimal String.
toOctalString()-->converts a number to octal String.
toBinaryString()-->converts a number to binary String.
equals()
--------
A equals is used to check whether 2 objects are equal or not,if equal returns true otherwise false.
It is available in Object class.
we can override equals as per program requirement.
Object class equals method is used to compare references but most of the predefined class override equals method for content(data) comparision.
ex:
String
All Wrappers
etc
override equals method for content comparision.
StringBuffer class equals performs refernce comparsion.
Program
-------
package com.manohar.java;
public class ArrayListDemo {
public static void main(String[] args) {
//case1
String s1="satya";
String s2="manohar";
System.out.println(s1.equals(s2));
//case2
StringBuffer b1=new StringBuffer("satya");
StringBuffer b2=new StringBuffer("satya");
System.out.println(b1.equals(b2));
}
}
LinkedList
----------
LinkedList implements List,Serializable,Cloneable,Queue
LinkedList is best for perorming insert operation and worst for performing retrieval operation.
It follows same properties of List.
LinkedList Specific Methods inherited from queue
------------------------------------------------
addFirst()
addLast()
removeFirst()
removeLast()
getFirst()
getLast()
The underlying datatstructure if LinkedList is double LinkedList.
It is introduced in 1.2 version.
Constructors
------------
LinkedList()
This creates an empty list.
LinkedList(Collection);
This accepts any collection.
Program
------
package com.manohar.java;
import java.util.LinkedList;
public class LinkedListDemo {
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.add(10);
// Adds element as a first element
list.addFirst(20);
// Adds eleement as a Last element
list.addLast(30);
list.add(40);
list.add(50);
list.add(60);
// get based on index
System.out.println(list.get(1));
// get first element
System.out.println(list.getFirst());
// get last element
System.out.println(list.getLast());
System.out.println(list);
// remove based on object
System.out.println(list.remove(1));
// remove First
System.out.println(list.removeFirst());
// remove Last
System.out.println(list.removeLast());
System.out.println(list);
}
}
output
------
10
20
60
[20, 10, 30, 40, 50, 60]
10
20
60
[30, 40, 50].
Vector
------
Vector is same as ArrayList with the following differences.
ArrayList Vector
---------- --------------
i)Not synchronized. i)Synchronized.
ii)Not thread safe ii)thread safe
iii)Best at performance iii)Low at performance.
iv)1.2 version iv)1.0 version.
Note:
Vector is a legacy class i,e it is introduced in 1.0 version of java.
It consists of the following legacy methods like
i)addElement()
ii)removeElement()
iii)addAllElements())
iv)capacity()
etc
Costructors
------------
Vector()
creates an empty Vector object with a default capacity 10.
Vector(Collection<? extends E> c)
This Constructor accepts any type of Collection
Vector(int initialCapacity)
creates an empty Vector object with a customized capacity.
Vector(int initialCapacity, int capacityIncrement)
creates an empty Vector object with a customized capacity and fill ratio.
We can calculate the load factor of ArrayList or Vector by using the formula
(initialcapacit*3/2)+1
10*3/2+1
16
16*3/2+1
25
The underlying datastructure of Vector is dynamic array.
Program
-------
package com.manohar.java;
import java.util.Vector;
public class VectorDemo {
public static void main(String[] args) {
Vector vector=new Vector();
System.out.println(vector.capacity());
vector.addElement(10);
vector.addElement(20);
vector.addElement(30);
vector.addElement(40);
vector.addElement(10);
System.out.println(vector.capacity());
for(int i=0;i<vector.size();i++){
System.out.println(vector.get(i));
}
System.out.println(vector);
}
}
Vector is also best fit for retrieval operation because it also implements
RandomAccess interface apart from List,Serializable,Cloneable.
Stack
-----
It is a child class of Vector.
It is introduced in 1.0 version
stack follows a principle Last in fisrt out[LIFO].
Methods
-------
public java.util.Stack();
creates a stack with empty list.
public Object push(E);
Adds an object to Stack.
public synchronized Object pop();
remove an object from Stack and returns.
public synchronized Object peek();
returns the top element.
public boolean empty();
checks whether a stack is empty.
public synchronized int search(java.lang.Object);
searches whether an element is available in stack or not.
returns position of the element from top ,if it is available in stack
otherwise it returns -1.
In Stack insertion and deletion is done through only one end called top.
Program
-------
package com.manohar.java;
import java.util.Stack;
public class StackDemo {
public static void main(String[] args) {
Stack stack=new Stack();
stack.push(10);
stack.push(20);
stack.push(30);
stack.push(40);
stack.push(50);
stack.push(60);
System.out.println(stack);
System.out.println(stack.pop());//60
System.out.println(stack);//
System.out.println(stack.peek());//50
System.out.println(stack);
System.out.println(stack.empty());//false
System.out.println(stack.search(new Integer(45)));
}
}
output
------
[10, 20, 30, 40, 50, 60]
60
[10, 20, 30, 40, 50]
50
[10, 20, 30, 40, 50]
false
-1
Iterators
---------
An iterator performs a repititive task.
Two types of iterators
i)control statements
ii)Collecton
Iterators in Control statements
while
do-while
for
Iterators in collections
for-each.
Enumeration.
Iterator.
ListIterator.
for-each
--------
It is applicable on both static collection and dynamic collelction.
syntax
------
for(datatype destination:source)
{
//statements
}
Here source must be collection type i,e either array or collection
Every time for-each is iterated one object\value from source is copied to local variable(destination).
Program
-------
package com.manohar.java;
public class ForEachDemo1 {
public static void main(String[] args) {
String s[]={"java","hadoop","salesforce","devops"};
for(String str:s){
System.out.println(str);
}
}
}
Program
-------
package com.manohar.java;
import java.util.ArrayList;
public class ForEachDemo1 {
public static void main(String[] args) {
ArrayList list=new ArrayList();
list.add(10);
list.add(20);
list.add(30);
list.add(40);
list.add(50);
for(Object obj:list){
System.out.println(obj);
}
}
}
Limitations of for-each
-----------------------
i)for-each doesn't provide predefined method support.
ii)for-each is used to perform only read operation.
iii)for-each is a uni directional cursor i,e
it performs iteration only in forward direction.
Iterators in collections
------------------------
Collection framework provides predefined
iterators to perfrom iteration on collection objects.
They are
i)Enumeration.[inteface]
ii)Iterator.[interface]
iii)ListIterator.[interface]
All the iterators provides predefined
method support in Collection Framework.
All the above 3 iterators are available in java.util.* package
Enumeration
-----------
It is introduced in 1.0 version.
It is applicable only on Vector and Stack because Enumeration is a legacy iterator,Vector and Stack are also legacy classes.
It is read-only/forward only cursor.
Method summary
--------------
public abstract boolean hasMoreElements();
This method checks whether an object is available in the collection or not and returns true if the object exists otherwise false.
public abstract Object nextElement();
This method moves the cursor to next element and returns that element.
How to get Enumeration object on Vector and Stack
-------------------------------------------------
we use the method elements() avaialble in Vector and Stack to get Enumeration object of Vector and Stack.
syntax
------
public Enumeration elements();
syntax
------
Enumeration enumeration=reference.elements();
Here reference is reference of a Vector or Stack.
Case study
----------
create Vector object and add objects
Get Enumeration object
Iterate using while
syntax
------
while(enumeration.hasMoreElements()){
//enumeration.nexElement();
}
Program
-------
package com.manohar.java;
import java.util.Enumeration;
import java.util.Vector;
public class ForEachDemo1 {
public static void main(String[] args) {
Vector list=new Vector();
list.add(10);
list.add(20);
list.add(30);
list.add(40);
list.add(50);
//step2
Enumeration e=list.elements();
//step3
while(e.hasMoreElements()){
System.out.println(e.nextElement());
}
}
}
Iterator
--------
It perfoms a repetitive task.
It is universal cursor i,e it is applicable on all Collections.
It peforms both read and remove operations.
It is forward only cursor.
1.2 version.
Method summary
--------------
public abstract boolean hasNext();
This method checks whether an object exist in collection or not ,returns true if object is available otherwise false.
public abstract Object next();
This method moves cursor to the next element in collection and returns that element.
public void remove();
remove an element from collection
public void forEachRemaining(java.util.function.Consumer<? super E>);
How to get iterator object of collection
------------------------------------
we get iteartor object of collection by using method
iterator() available in Collection interface.
Method signature
----------------
public Iterator iterator();
Getting iterator object
-----------------------
Iterator iterator=reference.iterator();
Here reference is reference of a collection class.
syntax
------
while(iterator.hasNext())
{
//
iterator.next();
}
Program
-------
package com.manohar.java;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
public class ForEachDemo1 {
public static void main(String[] args) {
ArrayList list = new ArrayList();
list.add("java");
list.add("coffee");
list.add("bru");
list.add("taj");
list.add("iphone");
list.add("umbrealla");
Iterator iterator = list.iterator();
while (iterator.hasNext()) {
String string = (String) iterator.next();
if (string.startsWith("a") || string.startsWith("e") || string.startsWith("i") || string.startsWith("o")
|| string.startsWith("u") || string.startsWith("A") || string.startsWith("E")
|| string.startsWith("I") || string.startsWith("O") || string.startsWith("U")) {
iterator.remove();
}
}
System.out.println(list);
}
}
ListIterator
------------
It is an interface.
It is applicable only on List classes.
A ListIterator is a child interface of Iterator.
ListIterator is the most powerful cursor among the cursors because it is bidirectional also we can perform read,write,update,remove operations using ListIterator.
Method summary
--------------
public abstract boolean hasNext();
checks whether an object exits in collection or not,returns true if the object is available otherwise false.
public abstract Object next();
Moves cursor next object and returns that object.
public abstract boolean hasPrevious()
checks whether an object exits in collection or not,returns true if the object is available otherwise false.
public abstract Object previous();
Position cursor to previous object and returns that object.
public abstract int nextIndex();
returns the next index of an object.
public abstract int previousIndex();
returns the previous index of an object.
public abstract void remove();
remove an object from collection.
public abstract void set(Object);
update an object in a collection.
public abstract void add(Object);
Adds an object to a collection.
How to get ListIterator object
------------------------------
We use the method listIterator() available in all List classes.
Method signature
----------------
public ListIterator listIterator();
syntax
------
ListIterator iterator=reference.listIterator();
ListIterator is applicable only on List implementation classes.
Program
-------
package com.manohar.java;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.ListIterator;
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList list=new ArrayList();
list.add(10);
list.add(20);
list.add(30);
list.add(40);
list.add(50);
//step2
ListIterator iterator=list.listIterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
}
}
Program
-------
package com.manohar.java;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.ListIterator;
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList list=new ArrayList();
list.add(10);
list.add(20);
list.add(30);
list.add(40);
list.add(50);
//step2
ListIterator iterator=list.listIterator(list.size());
while(iterator.hasPrevious()){
System.out.println(iterator.previous());
}
}
}
Note:
we should pass size of collection as a parameter to listIterator() so that we can perform navigation or iteration in both the directions.
Program
-------
package com.manohar.java;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.ListIterator;
import com.sun.corba.se.spi.orbutil.fsm.State;
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList list=new ArrayList();
list.add(1);
list.add(2);
list.add(20);
list.add(30);
list.add(400);
list.add(500);
//step2
ListIterator iterator=list.listIterator(list.size());
while(iterator.hasPrevious()){
int x=(int)iterator.previous();
if(x>=10&&x<100){
iterator.remove();
}
}
System.out.println(list);
}
}
Program
-------
package com.manohar.java;
//1-10
//After even no -->Add a string of that number
//After odd no -->replace that no with its String name
import java.util.ArrayList;
import java.util.ListIterator;
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList list = new ArrayList();
list.add(1);
list.add(2);
list.add(7);
list.add(8);
list.add(5);
// step2
ListIterator iterator = list.listIterator();
while (iterator.hasNext()) {
int x = (int) iterator.next();
if (x % 2 == 0) {
if (x == 2) {
iterator.add("Two");
} else if (x == 4) {
iterator.add("Four");
} else if (x == 6) {
iterator.add("six");
} else if (x == 8) {
iterator.add("Eight");
}
} else {
if (x == 1) {
iterator.set("one");
} else if (x == 3) {
iterator.set("Three");
} else if (x == 5) {
iterator.set("five");
} else if (x == 7) {
iterator.set("seven");
} else if (x == 9) {
iterator.set("nine");
}
}
}
System.out.println(list);
}
}
Note:
While iterating a collection using iterator we should perform operations on collection object using methods of iterator otherwise it leads to "ConcurrentModificationEXception".
How to get synchrinized version of ArrayList
--------------------------------------------
we can get synchronized version any List implementation by using the method synchronizedList() available in Collections class.
Method signature
----------------
public static List synchronizedList(List);
Example
-------
ArrayList list=new ArrayList();
list.add(10);
list.add(20);
list.add(30);
List list=Collections.synchronizedList(list);
Set collection
--------------
It is a child interface of Collection
Set heirarchy
-------------
Collection
|
Set--------------------------------
| | |
HashSet LinkedHashSet SortedSet
|
NavigableSet
|
TreeSet
dynamic yes
heterogenous\homogenous heterogenous except TreeSet
insertion order Not preserved except LinkedHashSet
duplicates Are not allowesd
null insertion Except TreeSet null insertion is possible for all Set classes.
HashSet
-------
Impl class of Set
It implments Set,Serializable,Colneable,Collection.
It is introduced in 1.2 version.
Underlying datastructure of HashSet is Hashtable
It is heterogenous.
Constructors of HashSet
-----------------------
HashSet()
creates empty HashSet() with initial default capacity 16 and loadfactor 0.75.
HashSet(Collection)
This accepts any collection as a parameter.
HashSet(int)
creates empty HashSet with userdefined capacity.
HashSet(int,float)
creates empty HashSet with userdefined capacity and loadfactor.
Program
-------
package com.manohar.java;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
public class DuplicateRemoveDemo {
public static void main(String[] args) {
HashSet set = new HashSet();
set.add(10);
set.add(11);
set.add(20);
set.add(21);
set.add(30);
set.add(40);
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
int x = (int) iterator.next();
if (x % 10 == 0) {
System.out.println(x);
}
}
}
}
display numbers starting with 1
display numbers ending with 1
LinkedHashSet
-------------
Introduced in 1.4 version.
It is same as HashSet except the underlying datastructure.
The unuderlying datastructure of LinkedHashSet is
LinkedList and Hashtable.
LinkedHashSet preserves insertion order.
constructor summary
-------------------
LinkedHashSet()
creates empty HashSet() with initial default capacity 16 and loadfactor 0.75.
LinkedHashSet(Collection)
This accepts any collection as a parameter.
LinkedHashSet(int)
creates empty HashSet with userdefined capacity.
LinkedHashSet(int,float)
creates empty HashSet with userdefined capacity and loadfactor.
Program
-------
package com.manohar.java;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
public class DuplicateRemoveDemo {
public static void main(String[] args) {
LinkedHashSet set = new LinkedHashSet();
set.add(10);
set.add(11);
set.add(20);
set.add(21);
set.add(30);
set.add(40);
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
int x = (int) iterator.next();
System.out.println(x);
}
}
}
output
------
10
11
20
21
30
40
Usage
-----
If we want to avoid duplicates and insertion order must be preserved then choose LinkedHashSet,if we don't
want to preserve insertion order and if we want to remove duplicates then choose HashSet.
SortedSet
---------
A SortedSet is a child interface.
SortedSet is used to avoid duplicates and sort elements of collection according to natural sorting order(ascending order).
It is child interface of Set.
It is introduced in 1.2 version.
Method summary
--------------
public abstract java.util.SortedSet<E> subSet(Object, Object);
returns set elements from starting object and upto ending object excluding ending object.
public abstract java.util.SortedSet<E> headSet(E);
returns head part of an collection.
public abstract java.util.SortedSet<E> tailSet(E);
returns tail part of a collection.
public abstract E first();
returns first element of a collection.
public abstract E last();
returns last element of a collection.
public java.util.Spliterator<E> spliterator();
similar to iterator.
TreeSet
-------
It is implementation class of Set,SortedSet,NavigableSet,Cloneable,Serializable.
If we want to avoid duplicates and sort elements according to natural sorting order then we should use TreeSet.
It is dynamic.
It is homogenous,if we try to insert heterogenous elements it leads to ClassCastException.
It doesn't allow duplicates.
Insertion order not preserved.
null insertion is not allowed in TreeSet,if we try to insert null values it leads to NullPointerException.
In the previous versions null insertion is possible in empty TreeSet but from 1.7 version onwards null insertion is not possible even in empty TreeSet also.
Program
-------
package com.manohar.java;
import java.util.TreeSet;
public class TreeSetDemo {
public static void main(String[] args) {
TreeSet set=new TreeSet();
set.add(10);
set.add(5);
set.add(20);
set.add(15);
set.add(19);
System.out.println(set);
System.out.println(set.subSet(5,15));//5,10
System.out.println(set.headSet(15));//5,10
System.out.println(set.tailSet(15));//5,10
System.out.println(set.first());
System.out.println(set.last());
}
}
output
------
[5, 10, 15, 19, 20]
[5, 10]
[5, 10]
[15, 19, 20]
5
20
NavigableSet
------------
It is child interface of SortedSet.
It provides methods to perform navigation of data.
Introduced in 1.6 version.
Method Summary
--------------
public abstract Object lower(Object);
returns lower element of an object i,e element less than the object.
public abstract Object floor(Object);
returns lower limit of an Object.
public abstract Object ceiling(Object);
returns upper limit of an Object.
public abstract Object higher(Object);
returns an higer element of an object i,e element greater than object.
public abstract Object pollFirst();
returns first element
public abstract Object pollLast();
returns last element.
public abstract java.util.Iterator<E> iterator();
public abstract java.util.NavigableSet<E> descendingSet();
displays elements in descending order.
Program
-------
package com.manohar.java;
import java.util.TreeSet;
public class TreeSetDemo {
public static void main(String[] args) {
TreeSet set=new TreeSet();
set.add(10);
set.add(5);
set.add(20);
set.add(15);
set.add(19);
System.out.println(set);
//methods of navigable set
System.out.println(set.lower(15));//
System.out.println(set.higher(15));//
System.out.println(set.pollFirst());//
System.out.println(set.pollLast());//
System.out.println(set.floor(16));
System.out.println(set.ceiling(18));
System.out.println(set);
//
System.out.println(Math.floor(10.6));//
System.out.println(Math.ceil(5.3));//
}
}
Note1:
If we try to insert heterogenous elements in a TreeSet it leads to ClassCastException.
Note2:
If we add a null value to a TreeSet it leads to NullPointerException.
Note3:
descendingSet() returns elements of set in descending order.
TreeSet set=new TreeSet();
set.add(10);
set.add(5);
set.add(20);
set.add(15);
set.add(19);
System.out.println(set.descendingSet());
Constructor summary of LinkedHashSet and TreeSet
------------------------------------------------
LinkedHashSet()
creates empty HashSet() with initial default capacity 16 and loadfactor 0.75.
LinkedHashSet(Collection)
This accepts any collection as a parameter.
LinkedHashSet(int)
creates empty HashSet with userdefined capacity.
LinkedHashSet(int,float)
creates empty HashSet with userdefined capacity and loadfactor.
TreeSet()
Creates empty tree set, sorted according to the natural ordering of its elements.
TreeSet(Collection<? extends E> c)
Used to copy elements of any other collection into TreeSet.
TreeSet(Comparator<? super E> comparator)
Creates a new empty tree set, and accepts as Comparator as a parameter.
TreeSet(SortedSet<E> s)
Creates a new tree and sorts elements according to SortedSet.
Underlying datastructure of TreeSet is Red-
black trees.
Comparable and Comparator interface
-----------------------------------
Comparable
----------
It is available in java.lang.*
If we want to go natural sorting then we should implement Comparable interface.
It consists of one method compareTo()
signature
---------
public int comparaeTO(object);
How access compareTo()
----------------------
obj1.compareTo(obj2);
case 1:
returns zero if both objects are same.
case2:retuns a negative value of object1 is less than object2 i,e unicode difference.
case3:
retuns a positive value of object1 is greater than object2 i,e unicode difference.
Natural sorting in TreeSet
--------------------------
Every time we add an element to TreeSet,jvm internally call compareTo() method to perform sorting of elements according to natural sorting order.
TreeSet set=new TreeSet();
set.add("A");
set.add("M");//"M".compareTo("A");+ve
set.add("B");//"B".compareTo("M");-ve
// "B".compareTo("A");+ve
System.out.println(set);
obj1-the latest element we add to TreeSet.
obj2-already existing object.
Note:
if -ve exchange of values happens in TreeSet
if +ve no need of any exchange.
Customized sorting int collections
----------------------------------
Comparator
----------
It is an interface available in java.util.* package.
We want to implement customized sorting then we should go for Comparator interface.
It consists of a method compare()
steps for implementing customized sorting in Comparator
------------------------------------------------------
step1:Implement Comparator interface in a class.
accessmodifier class ClassName implements Comparator
{
}
step2:override compare() method and apply comparision logic in Comparator class.
ex:
class MyComparator implements Comparator {
@Override
public int compare(Object obj1, Object obj2) {
String s1 = (String) obj1;
String s2 = (String) obj2;
return -s1.compareTo(s2);
}
}
step3:Create TreeSet object and pass Comparator object as a parameter to the constructor of TreeSet.
ex:
// step1
MyComparator comparator = new MyComparator();
//step2
TreeSet set = new TreeSet(comparator);
Program
-------
package com.manohar.java;
//step1
import java.util.Comparator;
import java.util.TreeSet;
class MyComparator1 implements Comparator
{
@Override
public int compare(Object o1, Object o2) {
String s1=(String)o1;
String s2=(String) o2;
return -s1.compareTo(s2);
}
}
public class ComparatorDemo {
public static void main(String[] args) {
//step2
MyComparator1 comparator1=new MyComparator1();
//step3
TreeSet set=new TreeSet(comparator1);
set.add("samantha");
set.add("deepika");
set.add("priyanka");
set.add("kajal");
set.add("rasi");
System.out.println(set);
}
}
output
------
[samantha, rasi, priyanka, kajal, deepika].
Pojo[Plain old java object]
---------------------------
It is a simple java class with private properties and public setters and getters.
It must have a default constructor.
It must implement a serializable interface.
creating setters and getters
----------------------------
setter methods
--------------
A setter method used to set value a to property of a pojo.
syntax
------
public void setPropertyName(datatype varname)
{
this.varname=varname;
}
getter methods
--------------
A getter method returns a value of a property.
syntax
------
public datatype getPropertyName()
{
return varname;
}
example
-------
class Employee implements Serializable
{
private String empName;
private int empID;
private double empSal;
//
public void setEmpName(String empName)
{
this.empName=empName;
}
public String getEmpName()
{
return empName;
}
}
display details 3 employees
---------------------------
create 3 objects for pojo
set values for all objects using setters.
get values throgh getters.
creating Array of objects
------------------------
Arrays can store both primitives and objects.
Program to create array of objects
----------------------------------
package com.manohar.pojo;
public class Employee {
//property declarations
private String empName;
private int empID;
private double empSal;
//creating setters and getters
}
package com.manohar.java;
import java.util.Scanner;
import com.manohar.pojo.Employee;
public class ArrayOfObjectsDemo {
public static void main(String[] args) {
//declaring array of references
Employee e[] = new Employee[2];//1
//creating objects
for(int i=0;i<e.length;i++){
e[i]=new Employee();//2
}
Scanner scanner = new Scanner(System.in);
// initializing all the objects
for (int i = 0; i < e.length; i++) {
System.out.println("enter name");
e[i].setEmpName(scanner.next());
System.out.println("enter id");
e[i].setEmpID(scanner.nextInt());
System.out.println("enter sal");
e[i].setEmpSal(scanner.nextDouble());
}
// displaying all the objects
for (int i = 0; i < e.length; i++) {
System.out.println(e[i].getEmpName());
System.out.println(e[i].getEmpID());
System.out.println(e[i].getEmpSal());
}
}
}
In the above code @line1 we are declaring Array of reference for Employee.
Whenever we declare an array by default it is initialized with default values.
similarly as Employee is a reference type it is initialized with null as shown in diagram.
Once we declare references we should initialize reference with objects as shown @line2 otherwise it leads to NullPointerException whenever perform operations on these null references.
we are initiazing all the obejcts using setters and getters as shown in loops.
Adding objects to collections and iterating objects from collection
----------
create 5 employee objects,initialize them using setters
add all the five employee objects to ArrayList/HashSet and display values from Employee by iterating collection.
package com.manohar.java;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;
import com.manohar.pojo.Employee;
public class ArrayOfObjectsDemo {
public static void main(String[] args) {
// declaring array of references
Employee e[] = new Employee[2];// line1
// creating objects
for (int i = 0; i < e.length; i++) {
e[i] = new Employee();// line2
}
Scanner scanner = new Scanner(System.in);
// initializing all the objects
for (int i = 0; i < e.length; i++) {
System.out.println("enter name");
e[i].setEmpName(scanner.next());
System.out.println("enter id");
e[i].setEmpID(scanner.nextInt());
System.out.println("enter sal");
e[i].setEmpSal(scanner.nextDouble());
}
ArrayList list = new ArrayList();
for (int i = 0; i < e.length; i++) {
list.add(e[i]);
}
Iterator iterator=list.iterator();
while(iterator.hasNext()){
Employee employee=(Employee) iterator.next();
System.out.println(employee.getEmpID());
System.out.println(employee.getEmpName());
System.out.println(employee.getEmpSal());
}
Iterator iterator2=list.iterator();
while(iterator2.hasNext()){
Employee e1=(Employee) iterator2.next();
System.out.println(e1);
}
}
}
Program
-------
package com.manohar.java;
import java.util.ArrayList;
import java.util.Iterator;
import com.manohar.pojo.Employee;
public class EmployeeTest {
public static void main(String[] args) {
Employee employee1=new Employee();
employee1.setEmpID(1001);
employee1.setEmpName("manohar");
employee1.setEmpSal(10000.00);
Employee employee2=new Employee();
employee2.setEmpID(1002);
employee2.setEmpName("prabhas");
employee2.setEmpSal(20000.00);
Employee employee3=new Employee();
employee3.setEmpID(1003);
employee3.setEmpName("mahesh");
employee3.setEmpSal(30000.00);
Employee employee4=new Employee();
employee4.setEmpID(1004);
employee4.setEmpName("pawan");
employee4.setEmpSal(40000.00);
Employee employee5=new Employee();
employee5.setEmpID(1005);
employee5.setEmpName("balayya");
employee5.setEmpSal(50000.00);
//create collection
ArrayList list=new ArrayList();
list.add(employee1);
list.add(employee2);
list.add(employee3);
list.add(employee4);
list.add(employee5);
Iterator iterator=list.iterator();
while(iterator.hasNext()){
Employee employee=(Employee) iterator.next();
System.out.println(employee.getEmpID());
System.out.println(employee.getEmpName());
System.out.println(employee.getEmpSal());
}
}
}
Sorting Userdefined using TreeSet
---------------------------------
If we want to add objects in TreeSet then the objects must be Comparable otherwise it leads to ClassCastException i,e the class must implement Comparable interface,objects created for such classes are only allowed in TreeSet.
Program
-------
Step1:create an Employee by implementing Comparable interface.
package com.manohar.java;
import java.io.Serializable;
public class Employee implements Serializable, Comparable {
private String name;
private int empID;
private double empSal;
//setters and getters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getEmpID() {
return empID;
}
public void setEmpID(int empID) {
this.empID = empID;
}
public double getEmpSal() {
return empSal;
}
public void setEmpSal(double empSal) {
this.empSal = empSal;
}
@Override
public int compareTo(Object obj) {
Employee employee = (Employee) obj;
if (this.empID < employee.empID) {
return -1;
}
else if (this.empID > employee.empID)
{
return +1;
} else {
return 0;
}
}
}
step2:creating Test class and passing Employee objects TreeSet whihc are sorting according to empid.
public class EmpTest {
public static void main(String[] args) {
Employee employee1 = new Employee();
employee1.setEmpID(1);
Employee employee2 = new Employee();
employee2.setEmpID(2);
Employee employee3 = new Employee();
employee3.setEmpID(3);
TreeSet set = new TreeSet();
set.add(employee1);
set.add(employee3);
set.add(employee2);
for(Object obj:set){
Employee employee=(Employee)obj;
System.out.println(employee.getEmpID());
}
System.out.println(set);
}
}
Customized sorting of userdefined objects
-----------------------------------------
package com.manohar.java;
import java.util.Comparator;
import java.util.TreeSet;
class MyComparator implements Comparator{
@Override
public int compare(Object obj1, Object obj2) {
Employee e1=(Employee)obj1;
Employee e2=(Employee)obj2;
return e2.compareTo(e1);
}
}
public class EmpTest {
public static void main(String[] args) {
Employee employee1 = new Employee();
employee1.setEmpID(1);
Employee employee2 = new Employee();
employee2.setEmpID(2);
Employee employee3 = new Employee();
employee3.setEmpID(3);
TreeSet set = new TreeSet(new MyComparator());
set.add(employee1);
set.add(employee3);
set.add(employee2);
for(Object obj:set){
Employee employee=(Employee)obj;
System.out.println(employee.getEmpID());
}
System.out.println(set);
}
}
write a program to sort employee objects according to employee name----------------------------------------
-------------
Queue[interface]
----------------
A queue inserts elements according to some priority and by default it follows a principle is First in First out[FIFO].
Properties
----------
dynamic
homogenous
insertion order is not preserved
duplicates are allowed
null is not possible in queue.
Method summary
--------------
public abstract boolean add(E);
adds an element to a queue.
public abstract boolean offer(E);
Adds an element to queue.
public abstract Object remove();
remove and retun object,if no element exist in queue throws an exception java.util.NoSuchElementException
public abstract Object poll();
remove and return element,returns null if no element exist in the queue.
public abstract Object element();
return first element,throws exception java.util.NoSuchElementException if no element exist in queue.
public abstract Object peek();
return first element,returns null if no element exist in queue.
PriorityQueue
-------------
It is an impl class of Queue interface.
Introduced in 1.5 version of java.
Program
-------
package com.manohar.java;
import java.util.PriorityQueue;
public class QueueDemo {
public static void main(String[] args) {
PriorityQueue queue=new PriorityQueue();
queue.offer(40);
queue.offer(30);
queue.offer(30);
queue.offer(10);
queue.offer(20);
queue.offer(30);
queue.add(40);
//removal methods
System.out.println(queue.remove());
System.out.println(queue.poll());
//examine elements
System.out.println(queue.element());
System.out.println(queue.peek());
System.out.println(queue);
}
}
Constructor summary
-------------------
PriorityQueue()
Creates a PriorityQueue with the default initial capacity (11) that orders its elements according to their natural ordering.
PriorityQueue(Collection<? extends E> c)
Creates a PriorityQueue containing the elements in the specified collection.
PriorityQueue(int initialCapacity)
Creates a PriorityQueue with the specified initial capacity that orders its elements according to their natural ordering.
PriorityQueue(int initialCapacity, Comparator<? super E> comparator)
Creates a PriorityQueue with the specified initial capacity that orders its elements according to the specified comparator.
PriorityQueue(PriorityQueue<? extends E> c)
Creates a PriorityQueue containing the elements in the specified priority queue.
PriorityQueue(SortedSet<? extends E> c)
Creates a PriorityQueue containing the elements in the specified sorted set.
Program
-------
package com.manohar.java;
import java.util.PriorityQueue;
public class QueueDemo {
public static void main(String[] args) {
PriorityQueue queue = new PriorityQueue();
queue.add(10);
queue.add(20);
queue.add(50);
queue.add(40);
queue.add(70);
queue.add(20);
queue.add(50);
queue.add(40);
queue.offer(100);
System.out.println(queue);
//removal of elemements
System.out.println(queue.remove());
System.out.println(queue.poll());
//examining elements
System.out.println(queue.element());
System.out.println(queue.peek());
System.out.println(queue);
}
}
Dequeue[double ended queue]
---------------------------
A deque is used to pefrom insert and delete operations from bothe the ends i,e rear and front end.Generally in a queue insertion is done through rear,deletion through front.
It is intorduced in 1.6 version.
It is a child interface of Queue
Method summary
--------------
//addition if elements to dequeue
public void addFirst(E);
public void addLast(E);
public boolean offerFirst(E);
public boolean offerLast(E);
//removal of elements from dequeue
public Object removeFirst();
public Object removeLast();
public Object pollFirst();
public Object pollLast();
public boolean removeFirstOccurrence(java.lang.Object);
public boolean removeLastOccurrence(java.lang.Object);
//examining the elements of queue
public abstract E getFirst();
public abstract E getLast();
public abstract E peekFirst();
public abstract E peekLast();
Implementation classes
----------------------
A Deque has the following implementation classes.
1)ArrayDeque.
2)ConcurrentLinkedDeque.
3)LinkedBlockingDeque.
4)LinkedList.
Program
-------
package com.manohar.java;
import java.util.LinkedList;
public class QueueTest {
public static void main(String[] args) {
LinkedList list=new LinkedList();
//addition of elements to dequeu
list.add(10);
list.add(20);
list.add(30);
list.addFirst(40);
list.addLast(50);
list.add(10);
list.offerFirst(60);
list.offerLast(70);
list.add(10);
System.out.println(list);
//removal
list.removeFirstOccurrence(10);
System.out.println(list);
list.removeLastOccurrence(10);
list.removeLast();
System.out.println(list);
list.removeFirst();
System.out.println(list);
list.pollFirst();
System.out.println(list);
list.pollLast();
System.out.println(list);
//examine
System.out.println(list.getFirst());
System.out.println(list.getLast());
System.out.println(list.peekFirst());
System.out.println(list.peekLast());
}
}
output
------
[60, 40, 10, 20, 30, 50, 10, 70, 10]
[60, 40, 20, 30, 50, 10, 70, 10]
[60, 40, 20, 30, 50, 10]
[40, 20, 30, 50, 10]
[20, 30, 50, 10]
[20, 30, 50]
20
50
20
50
Map
---
Map is an interface available in java.util.* package.
Map is represents objects in the form of
key-value pairs.
ex:
1--manohar
2--raghu
3--shekar
4--kvr
1--manohar
keys must be unique.
values can be duplicated.
Each key-value pair is called one entry.
-----
Map Heirarchy
-------------
Map
|
----------------------------------------------
^ | ^ ^ ^
| | | | |
HahsMap| LinkedHashMap IdentityHashMap SortedMap.
| ^
WeakHashMap |
NavigableMap.
^
|
TreeMap.
Note:Map and Collection are different heirachies.
Map is root interface of all Map's in java.
It is dynamic
It is used to represent group objects in the form of key and value pairs.
Methods of Map inteface
-----------------------
public int size();
returns size of Map.
public boolean isEmpty();
checks whether Map is empty or not.
public boolean containsKey(java.lang.Object);
checks whether a key is available in a map or not
returns true if available otherwise false.
public boolean containsValue(java.lang.Object);
checks whether a value is available in a map or not
returns true if available otherwise false.
public Object get(java.lang.Object);
returns a value of a key.
public Object put(K, V);
adds an entry to a Map.
public Object remove(java.lang.Object);
remove an object from a Map.
public void putAll(java.util.Map<? extends K, ? extends V>);
Add one Map to another Map.
public void clear();
clears a Map.
public java.util.Set<K> keySet();
returns Set of keys.
public java.util.Collection<V> values();
returns collection values
public java.util.Set<java.util.Map$Entry<K, V>> entrySet();
returns all entries in the form of Set.
public boolean equals(java.lang.Object);'
public int hashCode();
public Object getOrDefault(java.lang.Object, V);
returns a value of a key if it exists in a map otherwise returns default value specified by developer.
public boolean remove(java.lang.Object,
java.lang.Object);
public boolean replace(K, V, V);
public Object replace(K, V);
Map.Entry
---------
Entry is a inner interface of a Map.
A Map interface HAS-A Entry interface.
Entry provides methods to operate on an entry,it provides methods to read and update an entry in a Map.
syntax
------
interface Map
{
interface Entry
{
public K getKey();
//returns from entry
public V getValue();
//return value from entry
public V setValue(V);
//updates a value in entry
public boolean equals(java.lang.Object);
public int hashCode();
}
}
HashMap
-------
It is impl class of Map.
Introduced in 1.2 version of java.
Properties
----------
dynamic
Both keys and values are heterogenous.
Insertion order is not preserved because,objects are inserted into a Map based on HashCode of a keys.
keys must be unique,values can be duplicated.
null insertion is possible for both keys and values,but for keys null insertion is allowed only for one time.
underlying datastructure is Hashtable.
Constructor summary
-------------------
HashMap()
Creates an empty HashMap with the default initial capacity (16) and the default load factor (0.75).
HashMap(int initialCapacity)
Creates an empty HashMap with the specified initial capacity and the default load factor (0.75).
HashMap(int initialCapacity, float loadFactor)
Creates an empty HashMap with the specified initial capacity and load factor.
HashMap(Map<? extends K,? extends V> m)
Creates a new HashMap with the same mappings as the specified Map.
Program
-------
package com.manohar.java;
public class HashMapDemo {
public static void main(String[] args) {
HashMap map=new HashMap();
map.put(1,"manohar");
map.put(2, "manohar");
map.put(3, "manohar");
map.put(4, "kvr");
map.put(5, "venkatesh");
map.put(null,"sunil");
map.put(1,"sachin");
System.out.println(map);
System.out.println(map.size());//6
System.out.println(map.isEmpty());//false
System.out.println(map.containsKey(7));
System.out.println(map.containsValue("manohar"));
System.out.println(map.get(1));
System.out.println(map.remove(null));
System.out.println(map);
Set set=map.keySet();
System.out.println(set);
Collection collection=map.values();
System.out.println(collection);
System.out.println(map.getOrDefault(4,"xyz"));
System.out.println(map.replace(4,"kvr","manohar"));
System.out.println(map.replace(1,"virat"));
System.out.println(map);
}
}
Program
-------
package com.manohar.java;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
public class HashMapDemo {
public static void main(String[] args) {
HashMap map=new HashMap();
map.put(10,"orange");
map.put(2, "grapes");
map.put(3, "apple");
map.put(40, "pineapple");
map.put(5, "mango");
Set set=map.keySet();
Iterator iterator=set.iterator();
while(iterator.hasNext()){
int x=(int)iterator.next();
System.out.println(x+" "+map.get(x));
}
System.out.println(map);
}
}
Program
-------
package com.manohar.java;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
public class HashMapDemo1 {
public static void main(String[] args) {
HashMap map = new HashMap();
map.put(1, "manohar");
map.put(2, "raghu");
map.put(3, "shekar");
map.put(4, "kvr");
map.put(5, "manohar");
System.out.println(map);
Collection collection=map.values();
Set set=new HashSet(collection);
System.out.println(set);
}
}
Dictionary
^
|
Hashtable
^
|
Properties
Dictionary
----------
It is used to represent data in the form of key and value pairs.
It is a legacy class introduced in 1.0 version.
It is an abstract class.
Hashtable
---------
It is a child of Dictionary and impl class of Map.
1.0 version.
Properties
----------
dynamic.
Insertion order is not preserved.
null values are not allowed for both keys and values.
keys must be unique,values can be duplicated.
both keys and values can be heterogenous.
underlying datatstructure Hashtable.
It is a synchronized class.
It is threadsafe
Performance wise it is poor.
constructor summary
-------------------
Hashtable()
Creates a new, empty hashtable with a default initial capacity (11) and load factor (0.75).
Hashtable(int initialCapacity)
Creates a new, empty hashtable with the specified initial capacity and default load factor (0.75).
Hashtable(int initialCapacity, float loadFactor)
Creates a new, empty hashtable with the specified initial capacity and the specified load factor.
Hashtable(Map<? extends K,? extends V> t)
Creates a new hashtable with the same mappings as the given Map.
Program
-------
package com.manohar.java;
import java.util.Hashtable;
public class HashTableDemo {
public static void main(String[] args) {
Hashtable hashtable=new Hashtable();
hashtable.put(1,"samsung");
hashtable.put(2,"iphone");
hashtable.put("a",1);
hashtable.put(3,"nokia");
hashtable.put(4,"lg");
hashtable.put(5,"lenovo");
System.out.println(hashtable);
}
}
}
Properties
----------
A properties class is used to perform operations on a properties file like read,write,update and delete operations.
A properties file is used to represent properties like database connection,language,location etc
Program
-------
package com.manohar.java;
import java.util.Hashtable;
import java.util.Properties;
public class HashTableDemo {
public static void main(String[] args) {
Properties properties=new Properties();
properties.put(1,"rambo");
properties.put(2,"terminator");
properties.put(3,"matrix");
properties.put(4,"avengers");
properties.put(5,"expendables");
System.out.println(properties);
}
}
putAll()
--------
This is used to copy all the entries of one map to another map.
Program
-------
package com.manohar.java;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Properties;
public class HashTableDemo {
public static void main(String[] args) {
Properties properties=new Properties();
properties.put(1,"rambo");
properties.put(2,"terminator");
properties.put(3,"matrix");
properties.put(4,"avengers");
properties.put(5,"expendables");
System.out.println(properties);
HashMap map=new HashMap();
map.putAll(properties);
System.out.println(map);
}
}
Collection
----------
addAll()
Adds one collection to another collection.
removeAll()
remove one collection from another collection.
retainAll()
retains(keeps) common elements between 2 collections and removes uncommon elements of a collection.
containsAll()
checks whether one collection exists in another collection or not
Program
-------
package com.manohar.java;
import java.util.ArrayList;
public class MethodsDemo {
public static void main(String[] args) {
ArrayList list=new ArrayList();
list.add("dog");
list.add("cat");
list.add("tiger");
ArrayList list1=new ArrayList();
list1.add("rose");
list1.add("lilly");
list1.add("jasmine");
ArrayList list2=new ArrayList();
list2.add("rose");
list2.add("lilly");
list2.add("jasmine");
list2.add("sunflower");
list2.add("cauliflower");
list2.retainAll(list1);
System.out.println(list2);
list2.addAll(list);
System.out.println(list2);
System.out.println(list2.containsAll(list));
list2.removeAll(list);
System.out.println(list2.containsAll(list));
System.out.println(list2);
}
}
Utility classes in Collection
-----------------------------
we have 2 utility classes in java.util.* package
i)Collections
ii)Arrays
Collections
-----------
Collections is a class which provides methods to perform operations on collections like sorting,searching,reversing etc.
Method summary
--------------
public static void sort(List list);
public static void sort(List list, Comparator c).
public static int binarySearch(List list,Object key).
public static void copy(List dest,List src);.
public static Object max(Collection coll).
public static Object min(Collection coll).
public static void reverse(List list).
public static Comparator reverseOrder(Comparator).
Program
-------
package com.manohar.java;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class CollectionsDemo {
public static void main(String[] args) {
List list = new ArrayList(10);
list.add(10);
list.add(20);
list.add(5);
list.add(15);
list.add(9);
System.out.println(list);
List list2 = new ArrayList();
list2.add(50);
list2.add(60);
list2.add(70);
list2.add(50);
list2.add(60);
list2.add(70);
Collections.copy(list2, list);
System.out.println(list2);
Collections.sort(list2, Collections.reverseOrder());
System.out.println(list2);
Collections.sort(list);
System.out.println(list);
int key = 45;
int res = Collections.binarySearch(list, key);
System.out.println(res);
Collections.reverse(list);
System.out.println(list);
System.out.println(Collections.max(list));
System.out.println(Collections.min(list));
}
}
Note:if we are using copy method make sure the size of destination list is having bigger capacity than source list.
Note2:reverseOrder() method should be passed as a parameter to sort() method,sort() method will sort elements of List in ascending order,reverseOrder() will convert this ascending to descending.
Note3:while applying binary search make sure a List is sorted in ascending order.
Arrays
------
Arrays is an utilty class applicable in primitive arrays to perform sorting,searching etc.
public static void sort(array);
public static int binarySearch(array,key);
public boolean equals(array1,array2);
Program
-------
package com.manohar.java;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class CollectionsDemo {
public static void main(String[] args) {
String s[] = { "samantha", "kajal", "rakul", "suresh", "rashi" };
String s2[] = { "samantha", "kajal", "rakul", "suresh", "rashi" };
System.out.println(Arrays.equals(s, s2));
for (String str : s)
System.out.print(str + ",");
System.out.println();
Arrays.sort(s);
for (String str : s)
System.out.println(str + ",");
int res = Arrays.binarySearch(s, "suresh");
System.out.println(res);
List list=Arrays.asList(s);
System.out.println(list);
}
}
converting collection to array
------------------------------
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Hashtable;
import java.util.List;
public class MapDemo {
public static void main(String[] args) {
ArrayList l=new ArrayList();
l.add(10);
l.add(20);
l.add(30);
l.add(40);
l.add(50);
int a[]=new int[l.size()];
Object obj[]=l.toArray();
for(int i=0;i<obj.length;i++){
a[i]=(int)obj[i];
}
for(int i:a){
System.out.println(i);
}
}
}
Note:
asList() method converts array to List.
public class MapDemo {
public static void main(String[] args) {
String s[]={"inki","pinki","ponky"};
List list=Arrays.asList(s);
System.out.println(list);
}
}
Methods to synchronize List,Set,Map
-----------------------------------
To get synchornized version of List,Set,Map,Collections class provides following methods.
i) public List synchronizedList()
returns synchronizedList of any List class.
ii)public Set synchronizedSet()
returns synchronizedSet of any Set class.
iii)public Map synchronizedMap()
returns synchronizedMap of any Map class.
ArrayList l=new ArrayList();
l.add(10);
l.add(20);
l.add(30);
List list=Collections.synchronizedList(l);
simliary Apply for Set and Map
Generics
--------
Collections are heterogenous
We should always apply casting.
code:
ArrayList list=new ArrayList();
list.add(10);
list.add(20);
int x=(int)list.get(0);
get() returns object,if we don't apply casting properly then it may lead to ClassCastException.
Collection is not type safe.
Generic Collection
-------------------
generics provide type safety.
type casting is not necessary.
generics provides compiletime checking.
Generic respresentation of collection
-------------------------------------
We declare a generic representation by using diamond(<>) operator with collection.
syntax
------
ClassName<type> referencename=new ClassName<type>();
we should pass type as only reference type as a parameter to a generic collection,primitive are not accepted as a parameter.
Program
-------
public class GenDemo {
public static void main(String[] args) {
ArrayList<Integer> list=new ArrayList<Integer>();
list.add(10);
list.add(20);
list.add(30);
list.add(40);
list.add(50);
int x=list.get(0);//line1
System.out.println(x);
System.out.println(list);
}
}
In the above code we are getting value from ArrayList @line1 without applying any casting.
Generic respresentation of a Map
--------------------------------
ClassName<tyep1,type2> referencename=new ClassName<type1,type>();
Here we should represent type1 and type2 as class type or reference type.
Program
-------
public class GenDemo {
public static void main(String[] args) {
HashMap<Integer,String> map=new HashMap<Integer,String>();
map.put(1,"manohar");
map.put(2,"venkatesh");
map.put(3, "raghu");
map.put(4, "shekar");
map.put(5, "kvr");
System.out.println(map);
}
}
creating userdefined Generic class
----------------------------------
we should declare by using diamond operator with a classname shown in below.
syntax
------
accessmodifier class ClassName<E>
{
}
Here E is a generic type paramater which accepts any type of value like Integer,Float,Double,ClassType like Employee,Donkey,Monkey etc
we use the following standard names for parameter types
T - Type
E - Element
K - Key
N - Number
V - Value
Program
-------
class Test<T>
{
T a;
public void add(T a){
this.a=a;
}
public T get(){
return a;
}
}
public class GenDemo {
public static void main(String[] args) {
Test<Integer> t1=new Test<Integer>();
t1.add(10);
System.out.println(t1.get());
Test<String> t2=new Test<String>();
t2.add("how is it");
System.out.println(t2.get());
}
}
creating generic method
-----------------------
A generic method will any type of value.The parameter to a generic methods must be of generic type as shown below.
syntax
------
accessmodifier <T> returntype methidname(T t)
{
}
Program
-------
public class GenDemo {
public <T> void display(T t[]){
for(T t1:t){
System.out.println(t1);
}
}
public static void main(String[] args) {
Integer a[]={1,2,3,4,5};
new GenDemo().display(a);
}
}
Wild card characters in gererics
--------------------------------
Special symbols used with Collections are called Wild card charcaters.
? is the wild card character applied with collections.
In generic code, the question mark (?), called the wildcard, represents an unknown type
syntax
------
<? extends ClassName>
--------------------
Framework
---------
A framework is collection of interfaces,classes and enum.
Arrays
------
Collection of homogenous elements.
Arrays are type safe.
Performance is good.
Arrays holds both primitives and objects.
Limitations
-----------
i)Arrays are static in nature i,e fixed in size i,e they are not automatically growable and shrinkable.
ii)Arrays are not heterogenous.
iii)No predefined method support to work with arrays.
Collection
----------
A collection is representing group of objects as a single entity.
A collection stores only objects.
Collection allows heterogenous elements.
Collection is dynamic i,e automatically growable and shrinkable.
Collection provides predefined method support.
Limitations
-----------
Collection is not type safe.
Performance is low because of convertions internally from primitive to object and object to primitive.
if we want work with built-in datastructures Collection framework provides classes and interfaces to work with datastructres.
Collection framework is used to process data while performing database operations in java project,it is also to process huge data in general appliactions(Non-database applications).
Collection interface
--------------------
A Collection is root interface of all collections.
Collection interface consists of methods which are common for the entire Collections.
All Collections are available in java.util.*
Methods summary of Collection interface
---------------------------------------
public abstract int size();
returns size of collection
public abstract boolean isEmpty();
returns true if collection is empty otherwise false.
public abstract boolean contains(java.lang.Object);
checks whether an object is available in a collcetion or not returns true if it available otherwise false.
public abstract java.util.Iterator<E> iterator();
This method returns iterator object.
public abstract java.lang.Object[] toArray();
convert collection to Array.
public abstract boolean add(java.lang.Object);
adds an objectto collection.
public abstract boolean remove(java.lang.Object);
remove an object from collection.
public abstract boolean containsAll(java.util.Collection<?>);
checks whether a Collection is available in another collection or not returns true if it available otherwise false.
public abstract boolean addAll(java.util.Collection<? extends E>);
This is used to add a Collection to another collection.
public abstract boolean removeAll(java.util.Collection<?>);
This is used to remove a collection object from a another collection.
public abstract boolean retainAll(java.util.Collection<?>);
public abstract void clear();
clears collections.
public abstract boolean equals(java.lang.Object);
Used to check whether 2 objects are same or not returns true if both the objects are same otherwise false.
public abstract int hashCode();
returns hashCode of a collection.
List
----
It is child interface of collection.
Properties
----------
List is dynamic i,e it is growable and shrinkable.
List is heterogenous.
List allows duplicate values.
List preserves insertion order.
List allows null values.
Implementation classes of List
------------------------------
A List is implemented in the following classes.
i)ArrayList
ii)LinkedList
iii)Vector
iv)Stack
Collection
^
|
List
| | |
ArrayList LinkedList Vector
|
Stack
Methods of List interface
-------------------------
public abstract Object get(int);
It is used to get an object from List.
public abstract Object set(int, Object);
used to set or update an object in a List
public abstract void add(int, Object);
Adds an object at a given index.
public abstract Object remove(int);
remove an object at a given index.
public abstract int indexOf(java.lang.Object);
returns index of an object.
ArrayList
---------
It is implementation class of List interface
The underlying datastructure of ArrayList is dynamic array.
Constructors
------------
public java.util.ArrayList(int);
creates an ArrayList with customized capacity.
public java.util.ArrayList();
creates an ArrayList with default capacity.
public java.util.ArrayList(java.util.Collection<? extends E>
This is used to copy any collection to ArrayList.
The default capacity of ArrayList is 10.
ArrayList is introduced in 1.2 version.
ArrayList also implements the following interfaces
i)RandonAccess.
ii)Serializable.
iii)Cloneable.
RandomAccess
------------
This interface makes ArrayList efficient in performing retrieval operation.
Serializable
------------
If we implement Serializable interface then we can write an object to a file or we can send an object through a network.
Cloneable
---------
This allows us to create an exact copy of an object which we call this as cloning.
The above 3 interfaces are called marker interfaces.
Marker interface
----------------
A marker interface is an interface without any methods.
A marker interface provides additional capability to objects.
public interface RandomAccess
{
}
Program to demonstrate ArrayList
--------------------------------
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList list=new ArrayList();
list.add(10);
list.add(20.5);
list.add("Manohar");
list.add(true);
list.add(null);
list.add(10);
System.out.println(list);
}
Program
-------
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList list = new ArrayList();
list.add(10);
list.add(20.5);
list.add("Manohar");
list.add("JavaBali");
list.add(true);
list.add(null);
list.add(10);
System.out.println(list);
System.out.println("The size is " + list.size());
System.out.println("Is empty " + list.isEmpty());
System.out.println("contains " + list.contains("Manohar"));
//object based removal
System.out.println(list.remove(new Integer(10)));
System.out.println(list);
//index based removal
System.out.println(list.remove(4));
System.out.println(list);
//get
Object obj=list.get(3);
System.out.println(obj);
System.out.println(list.get(4));
//set
list.set(3,"Bull");
System.out.println(list);
list.add(2,"Bahubali");
System.out.println(list);
}
}
}
Program
-------
package com.manohar.java;
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList l=new ArrayList();
l.add(10);
l.add(20);
l.add(30);
l.add(40);
l.add(50);
//displaying size
System.out.println(l.size());//5
//adding object at a given index
l.add(3,35);
System.out.println(l);
//displaying size
System.out.println(l.size());//6
//remove based on index
l.remove(4);
System.out.println(l);
//displaying size
System.out.println(l.size());//5
//remove based on object
l.remove(new Integer(20));
System.out.println(l);
//displaying size
System.out.println(l.size());//5
//contains
System.out.println(l.contains(new Integer(50)));
//toArray
Object obj[]=l.toArray();
for(int i=0;i<obj.length;i++){
System.out.println(obj[i]);
}
//get()
System.out.println("get "+l.get(2));
//set
l.set(2,new Integer(70));
System.out.println(l);
//indexof
System.out.println(l.indexOf(30));
//lastindexof
System.out.println(l.lastIndexOf(70));
//isEmpty
System.out.println(l.isEmpty());
//retains
l.clear();
System.out.println(l);
}
}
i)add() method is represented in 2 forms
add(Object)-->This method will add an object sequentially in a collection.
add(int,object)-->This method add an element at a given index,here the object in the existing location is moved to next location from current location.
set(int,object)->it replaces old element with new element.
remove(Object)-->this method removes an object from a List directly.
remove(int)-->this removes an object based on index,here we should pass int as a value,if the size exceeds it leads to an exception
IndexOutOfBoundsException
case1
-----
package com.manohar.java;
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList l = new ArrayList();
l.add(10);
l.add(20);
l.add(30);
l.add(40);
l.add(50);
for(int i=0;i<l.size();i++)
{
System.out.println(obj);
}
}
}
case2
-----
package com.manohar.java;
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList l = new ArrayList();
l.add(10);
l.add(20);
l.add(30);
l.add(40);
l.add(50);
for(int i=0;i<l.size();i++)
{
Object obj = l.get(i);
System.out.println(obj);
}
}
}
case3
-----
package com.manohar.java;
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList l = new ArrayList();
l.add(10);
l.add(20);
l.add(30);
l.add(40);
l.add(50);
for(int i=0;i<l.size();i++)
{
Object obj = l.get(i);
Integer integer=(Integer)obj;
System.out.println(integer);
}
}
}
case4
-----
package com.manohar.java;
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList l = new ArrayList();
l.add(10);
l.add(20);
l.add(30);
l.add(40);
l.add(50);
for(int i=0;i<l.size();i++)
{
Object obj = l.get(i);
Integer integer=(Integer)obj;
int x=integer.intValue();
int y=integer;
System.out.println(x);
System.out.println(y);
}
}
}
case5
-----
package com.manohar.java;
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList l = new ArrayList();
l.add(10);
l.add(20);
l.add(30);
l.add(40);
l.add(50);
for(int i=0;i<l.size();i++)
{
int val=(int)l.get(i);
System.out.println(val);
}
}
}
Program
-------
package com.manohar.java;
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList l = new ArrayList();
l.add(10);
l.add(11);
l.add(20);
l.add(21);
l.add(30);
l.add(40);
l.add(50);
for (int i = 0; i < l.size(); i++) {
int val = (int) l.get(i);
if (val % 2 == 0) {
System.out.println(val);
}
}
}
}
case7
-----
We can apply casting for related objects otherwise it leads to ClassCastException.
package com.manohar.java;
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String[] args) {
Object obj=10.6;
int val=(int)obj;
System.out.println(val);
}
}
Output
------
Exception in thread "main" java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.Integer
Program
-------
package com.manohar.java;
import java.util.ArrayList;
import java.util.Scanner;
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList l = new ArrayList();
l.add(10);
l.add(11);
l.add(20);
l.add(21);
l.add(30);
l.add(40);
l.add(50);
System.out.println("enter val");
int val=new Scanner(System.in).nextInt();
boolean b=l.contains(val);
if(b){
int index=l.indexOf(val);
System.out.println(index);
System.out.println(l.get(index));
}
else{
System.out.println("element not found");
}
}
}
tostring()
equals()
hashCode()
toString()
----------
toString() is used to convert an object to a String object.
toString method is available in Object class.
whenever we print reference of object the hashcode of an object is displayed in hexadecimal form.
package com.manohar.java;
class Test
{
}
public class ArrayListDemo {
public static void main(String[] args) {
Test t=new Test();
System.out.println(t);//line1
}
}
output
------
com.manohar.java.Test@15db9742
Here the hashcode is represented in hexa form as
packagename.classname@hexacode.
In the above at line we are printing reference of Test class.
Whenever we print reference of an object the print statement internally calls toString() of object which returns hashcode.
we can override toString() method and display userdefined hascode as per program requirement.
Program
-------
package com.manohar.java;
class Test
{
public String toString()
{
Integer val=(int) (Math.random()*1000);
return val.toString();
//return (int)(Math.random()*100000)+"";
}
}
public class ArrayListDemo {
public static void main(String[] args) {
Test t=new Test();
System.out.println(t);
}
}
random() generates a random value from 0.1 to 0.9.
output
------
78890
hashCode()
----------
A hashCode() method returns integer representation of a hashcode().
It is available in object class.
package com.manohar.java;
class Test {
}
public class ArrayListDemo {
public static void main(String[] args) {
Test t = new Test();
System.out.println(t.hashCode());
}
}
output
------
366712642
toString() method of object class calls hashCode() internally and this is converted to String form and returned by toString() method.
A developer also can override hashCode() method and call it from toString().
Program
-------
package com.manohar.java;
class Test {
public int hashCode(){
double val=Math.random()*1000000;
return (int)val;
}
public String toString()
{
return Integer.toHexString(hashCode())+"";
}
}
public class ArrayListDemo {
public static void main(String[] args) {
Test t = new Test();
System.out.println(t);
}
}
output
------
c6ed0
we can convert a hashcode into hexa\octal\binary by using methods in wrapper class.They are
toHexString()-->converts a number to hexa decimal String.
toOctalString()-->converts a number to octal String.
toBinaryString()-->converts a number to binary String.
equals()
--------
A equals is used to check whether 2 objects are equal or not,if equal returns true otherwise false.
It is available in Object class.
we can override equals as per program requirement.
Object class equals method is used to compare references but most of the predefined class override equals method for content(data) comparision.
ex:
String
All Wrappers
etc
override equals method for content comparision.
StringBuffer class equals performs refernce comparsion.
Program
-------
package com.manohar.java;
public class ArrayListDemo {
public static void main(String[] args) {
//case1
String s1="satya";
String s2="manohar";
System.out.println(s1.equals(s2));
//case2
StringBuffer b1=new StringBuffer("satya");
StringBuffer b2=new StringBuffer("satya");
System.out.println(b1.equals(b2));
}
}
LinkedList
----------
LinkedList implements List,Serializable,Cloneable,Queue
LinkedList is best for perorming insert operation and worst for performing retrieval operation.
It follows same properties of List.
LinkedList Specific Methods inherited from queue
------------------------------------------------
addFirst()
addLast()
removeFirst()
removeLast()
getFirst()
getLast()
The underlying datatstructure if LinkedList is double LinkedList.
It is introduced in 1.2 version.
Constructors
------------
LinkedList()
This creates an empty list.
LinkedList(Collection);
This accepts any collection.
Program
------
package com.manohar.java;
import java.util.LinkedList;
public class LinkedListDemo {
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.add(10);
// Adds element as a first element
list.addFirst(20);
// Adds eleement as a Last element
list.addLast(30);
list.add(40);
list.add(50);
list.add(60);
// get based on index
System.out.println(list.get(1));
// get first element
System.out.println(list.getFirst());
// get last element
System.out.println(list.getLast());
System.out.println(list);
// remove based on object
System.out.println(list.remove(1));
// remove First
System.out.println(list.removeFirst());
// remove Last
System.out.println(list.removeLast());
System.out.println(list);
}
}
output
------
10
20
60
[20, 10, 30, 40, 50, 60]
10
20
60
[30, 40, 50].
Vector
------
Vector is same as ArrayList with the following differences.
ArrayList Vector
---------- --------------
i)Not synchronized. i)Synchronized.
ii)Not thread safe ii)thread safe
iii)Best at performance iii)Low at performance.
iv)1.2 version iv)1.0 version.
Note:
Vector is a legacy class i,e it is introduced in 1.0 version of java.
It consists of the following legacy methods like
i)addElement()
ii)removeElement()
iii)addAllElements())
iv)capacity()
etc
Costructors
------------
Vector()
creates an empty Vector object with a default capacity 10.
Vector(Collection<? extends E> c)
This Constructor accepts any type of Collection
Vector(int initialCapacity)
creates an empty Vector object with a customized capacity.
Vector(int initialCapacity, int capacityIncrement)
creates an empty Vector object with a customized capacity and fill ratio.
We can calculate the load factor of ArrayList or Vector by using the formula
(initialcapacit*3/2)+1
10*3/2+1
16
16*3/2+1
25
The underlying datastructure of Vector is dynamic array.
Program
-------
package com.manohar.java;
import java.util.Vector;
public class VectorDemo {
public static void main(String[] args) {
Vector vector=new Vector();
System.out.println(vector.capacity());
vector.addElement(10);
vector.addElement(20);
vector.addElement(30);
vector.addElement(40);
vector.addElement(10);
System.out.println(vector.capacity());
for(int i=0;i<vector.size();i++){
System.out.println(vector.get(i));
}
System.out.println(vector);
}
}
Vector is also best fit for retrieval operation because it also implements
RandomAccess interface apart from List,Serializable,Cloneable.
Stack
-----
It is a child class of Vector.
It is introduced in 1.0 version
stack follows a principle Last in fisrt out[LIFO].
Methods
-------
public java.util.Stack();
creates a stack with empty list.
public Object push(E);
Adds an object to Stack.
public synchronized Object pop();
remove an object from Stack and returns.
public synchronized Object peek();
returns the top element.
public boolean empty();
checks whether a stack is empty.
public synchronized int search(java.lang.Object);
searches whether an element is available in stack or not.
returns position of the element from top ,if it is available in stack
otherwise it returns -1.
In Stack insertion and deletion is done through only one end called top.
Program
-------
package com.manohar.java;
import java.util.Stack;
public class StackDemo {
public static void main(String[] args) {
Stack stack=new Stack();
stack.push(10);
stack.push(20);
stack.push(30);
stack.push(40);
stack.push(50);
stack.push(60);
System.out.println(stack);
System.out.println(stack.pop());//60
System.out.println(stack);//
System.out.println(stack.peek());//50
System.out.println(stack);
System.out.println(stack.empty());//false
System.out.println(stack.search(new Integer(45)));
}
}
output
------
[10, 20, 30, 40, 50, 60]
60
[10, 20, 30, 40, 50]
50
[10, 20, 30, 40, 50]
false
-1
Iterators
---------
An iterator performs a repititive task.
Two types of iterators
i)control statements
ii)Collecton
Iterators in Control statements
while
do-while
for
Iterators in collections
for-each.
Enumeration.
Iterator.
ListIterator.
for-each
--------
It is applicable on both static collection and dynamic collelction.
syntax
------
for(datatype destination:source)
{
//statements
}
Here source must be collection type i,e either array or collection
Every time for-each is iterated one object\value from source is copied to local variable(destination).
Program
-------
package com.manohar.java;
public class ForEachDemo1 {
public static void main(String[] args) {
String s[]={"java","hadoop","salesforce","devops"};
for(String str:s){
System.out.println(str);
}
}
}
Program
-------
package com.manohar.java;
import java.util.ArrayList;
public class ForEachDemo1 {
public static void main(String[] args) {
ArrayList list=new ArrayList();
list.add(10);
list.add(20);
list.add(30);
list.add(40);
list.add(50);
for(Object obj:list){
System.out.println(obj);
}
}
}
Limitations of for-each
-----------------------
i)for-each doesn't provide predefined method support.
ii)for-each is used to perform only read operation.
iii)for-each is a uni directional cursor i,e
it performs iteration only in forward direction.
Iterators in collections
------------------------
Collection framework provides predefined
iterators to perfrom iteration on collection objects.
They are
i)Enumeration.[inteface]
ii)Iterator.[interface]
iii)ListIterator.[interface]
All the iterators provides predefined
method support in Collection Framework.
All the above 3 iterators are available in java.util.* package
Enumeration
-----------
It is introduced in 1.0 version.
It is applicable only on Vector and Stack because Enumeration is a legacy iterator,Vector and Stack are also legacy classes.
It is read-only/forward only cursor.
Method summary
--------------
public abstract boolean hasMoreElements();
This method checks whether an object is available in the collection or not and returns true if the object exists otherwise false.
public abstract Object nextElement();
This method moves the cursor to next element and returns that element.
How to get Enumeration object on Vector and Stack
-------------------------------------------------
we use the method elements() avaialble in Vector and Stack to get Enumeration object of Vector and Stack.
syntax
------
public Enumeration elements();
syntax
------
Enumeration enumeration=reference.elements();
Here reference is reference of a Vector or Stack.
Case study
----------
create Vector object and add objects
Get Enumeration object
Iterate using while
syntax
------
while(enumeration.hasMoreElements()){
//enumeration.nexElement();
}
Program
-------
package com.manohar.java;
import java.util.Enumeration;
import java.util.Vector;
public class ForEachDemo1 {
public static void main(String[] args) {
Vector list=new Vector();
list.add(10);
list.add(20);
list.add(30);
list.add(40);
list.add(50);
//step2
Enumeration e=list.elements();
//step3
while(e.hasMoreElements()){
System.out.println(e.nextElement());
}
}
}
Iterator
--------
It perfoms a repetitive task.
It is universal cursor i,e it is applicable on all Collections.
It peforms both read and remove operations.
It is forward only cursor.
1.2 version.
Method summary
--------------
public abstract boolean hasNext();
This method checks whether an object exist in collection or not ,returns true if object is available otherwise false.
public abstract Object next();
This method moves cursor to the next element in collection and returns that element.
public void remove();
remove an element from collection
public void forEachRemaining(java.util.function.Consumer<? super E>);
How to get iterator object of collection
------------------------------------
we get iteartor object of collection by using method
iterator() available in Collection interface.
Method signature
----------------
public Iterator iterator();
Getting iterator object
-----------------------
Iterator iterator=reference.iterator();
Here reference is reference of a collection class.
syntax
------
while(iterator.hasNext())
{
//
iterator.next();
}
Program
-------
package com.manohar.java;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
public class ForEachDemo1 {
public static void main(String[] args) {
ArrayList list = new ArrayList();
list.add("java");
list.add("coffee");
list.add("bru");
list.add("taj");
list.add("iphone");
list.add("umbrealla");
Iterator iterator = list.iterator();
while (iterator.hasNext()) {
String string = (String) iterator.next();
if (string.startsWith("a") || string.startsWith("e") || string.startsWith("i") || string.startsWith("o")
|| string.startsWith("u") || string.startsWith("A") || string.startsWith("E")
|| string.startsWith("I") || string.startsWith("O") || string.startsWith("U")) {
iterator.remove();
}
}
System.out.println(list);
}
}
ListIterator
------------
It is an interface.
It is applicable only on List classes.
A ListIterator is a child interface of Iterator.
ListIterator is the most powerful cursor among the cursors because it is bidirectional also we can perform read,write,update,remove operations using ListIterator.
Method summary
--------------
public abstract boolean hasNext();
checks whether an object exits in collection or not,returns true if the object is available otherwise false.
public abstract Object next();
Moves cursor next object and returns that object.
public abstract boolean hasPrevious()
checks whether an object exits in collection or not,returns true if the object is available otherwise false.
public abstract Object previous();
Position cursor to previous object and returns that object.
public abstract int nextIndex();
returns the next index of an object.
public abstract int previousIndex();
returns the previous index of an object.
public abstract void remove();
remove an object from collection.
public abstract void set(Object);
update an object in a collection.
public abstract void add(Object);
Adds an object to a collection.
How to get ListIterator object
------------------------------
We use the method listIterator() available in all List classes.
Method signature
----------------
public ListIterator listIterator();
syntax
------
ListIterator iterator=reference.listIterator();
ListIterator is applicable only on List implementation classes.
Program
-------
package com.manohar.java;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.ListIterator;
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList list=new ArrayList();
list.add(10);
list.add(20);
list.add(30);
list.add(40);
list.add(50);
//step2
ListIterator iterator=list.listIterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
}
}
Program
-------
package com.manohar.java;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.ListIterator;
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList list=new ArrayList();
list.add(10);
list.add(20);
list.add(30);
list.add(40);
list.add(50);
//step2
ListIterator iterator=list.listIterator(list.size());
while(iterator.hasPrevious()){
System.out.println(iterator.previous());
}
}
}
Note:
we should pass size of collection as a parameter to listIterator() so that we can perform navigation or iteration in both the directions.
Program
-------
package com.manohar.java;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.ListIterator;
import com.sun.corba.se.spi.orbutil.fsm.State;
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList list=new ArrayList();
list.add(1);
list.add(2);
list.add(20);
list.add(30);
list.add(400);
list.add(500);
//step2
ListIterator iterator=list.listIterator(list.size());
while(iterator.hasPrevious()){
int x=(int)iterator.previous();
if(x>=10&&x<100){
iterator.remove();
}
}
System.out.println(list);
}
}
Program
-------
package com.manohar.java;
//1-10
//After even no -->Add a string of that number
//After odd no -->replace that no with its String name
import java.util.ArrayList;
import java.util.ListIterator;
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList list = new ArrayList();
list.add(1);
list.add(2);
list.add(7);
list.add(8);
list.add(5);
// step2
ListIterator iterator = list.listIterator();
while (iterator.hasNext()) {
int x = (int) iterator.next();
if (x % 2 == 0) {
if (x == 2) {
iterator.add("Two");
} else if (x == 4) {
iterator.add("Four");
} else if (x == 6) {
iterator.add("six");
} else if (x == 8) {
iterator.add("Eight");
}
} else {
if (x == 1) {
iterator.set("one");
} else if (x == 3) {
iterator.set("Three");
} else if (x == 5) {
iterator.set("five");
} else if (x == 7) {
iterator.set("seven");
} else if (x == 9) {
iterator.set("nine");
}
}
}
System.out.println(list);
}
}
Note:
While iterating a collection using iterator we should perform operations on collection object using methods of iterator otherwise it leads to "ConcurrentModificationEXception".
How to get synchrinized version of ArrayList
--------------------------------------------
we can get synchronized version any List implementation by using the method synchronizedList() available in Collections class.
Method signature
----------------
public static List synchronizedList(List);
Example
-------
ArrayList list=new ArrayList();
list.add(10);
list.add(20);
list.add(30);
List list=Collections.synchronizedList(list);
Set collection
--------------
It is a child interface of Collection
Set heirarchy
-------------
Collection
|
Set--------------------------------
| | |
HashSet LinkedHashSet SortedSet
|
NavigableSet
|
TreeSet
dynamic yes
heterogenous\homogenous heterogenous except TreeSet
insertion order Not preserved except LinkedHashSet
duplicates Are not allowesd
null insertion Except TreeSet null insertion is possible for all Set classes.
HashSet
-------
Impl class of Set
It implments Set,Serializable,Colneable,Collection.
It is introduced in 1.2 version.
Underlying datastructure of HashSet is Hashtable
It is heterogenous.
Constructors of HashSet
-----------------------
HashSet()
creates empty HashSet() with initial default capacity 16 and loadfactor 0.75.
HashSet(Collection)
This accepts any collection as a parameter.
HashSet(int)
creates empty HashSet with userdefined capacity.
HashSet(int,float)
creates empty HashSet with userdefined capacity and loadfactor.
Program
-------
package com.manohar.java;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
public class DuplicateRemoveDemo {
public static void main(String[] args) {
HashSet set = new HashSet();
set.add(10);
set.add(11);
set.add(20);
set.add(21);
set.add(30);
set.add(40);
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
int x = (int) iterator.next();
if (x % 10 == 0) {
System.out.println(x);
}
}
}
}
display numbers starting with 1
display numbers ending with 1
LinkedHashSet
-------------
Introduced in 1.4 version.
It is same as HashSet except the underlying datastructure.
The unuderlying datastructure of LinkedHashSet is
LinkedList and Hashtable.
LinkedHashSet preserves insertion order.
constructor summary
-------------------
LinkedHashSet()
creates empty HashSet() with initial default capacity 16 and loadfactor 0.75.
LinkedHashSet(Collection)
This accepts any collection as a parameter.
LinkedHashSet(int)
creates empty HashSet with userdefined capacity.
LinkedHashSet(int,float)
creates empty HashSet with userdefined capacity and loadfactor.
Program
-------
package com.manohar.java;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
public class DuplicateRemoveDemo {
public static void main(String[] args) {
LinkedHashSet set = new LinkedHashSet();
set.add(10);
set.add(11);
set.add(20);
set.add(21);
set.add(30);
set.add(40);
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
int x = (int) iterator.next();
System.out.println(x);
}
}
}
output
------
10
11
20
21
30
40
Usage
-----
If we want to avoid duplicates and insertion order must be preserved then choose LinkedHashSet,if we don't
want to preserve insertion order and if we want to remove duplicates then choose HashSet.
SortedSet
---------
A SortedSet is a child interface.
SortedSet is used to avoid duplicates and sort elements of collection according to natural sorting order(ascending order).
It is child interface of Set.
It is introduced in 1.2 version.
Method summary
--------------
public abstract java.util.SortedSet<E> subSet(Object, Object);
returns set elements from starting object and upto ending object excluding ending object.
public abstract java.util.SortedSet<E> headSet(E);
returns head part of an collection.
public abstract java.util.SortedSet<E> tailSet(E);
returns tail part of a collection.
public abstract E first();
returns first element of a collection.
public abstract E last();
returns last element of a collection.
public java.util.Spliterator<E> spliterator();
similar to iterator.
TreeSet
-------
It is implementation class of Set,SortedSet,NavigableSet,Cloneable,Serializable.
If we want to avoid duplicates and sort elements according to natural sorting order then we should use TreeSet.
It is dynamic.
It is homogenous,if we try to insert heterogenous elements it leads to ClassCastException.
It doesn't allow duplicates.
Insertion order not preserved.
null insertion is not allowed in TreeSet,if we try to insert null values it leads to NullPointerException.
In the previous versions null insertion is possible in empty TreeSet but from 1.7 version onwards null insertion is not possible even in empty TreeSet also.
Program
-------
package com.manohar.java;
import java.util.TreeSet;
public class TreeSetDemo {
public static void main(String[] args) {
TreeSet set=new TreeSet();
set.add(10);
set.add(5);
set.add(20);
set.add(15);
set.add(19);
System.out.println(set);
System.out.println(set.subSet(5,15));//5,10
System.out.println(set.headSet(15));//5,10
System.out.println(set.tailSet(15));//5,10
System.out.println(set.first());
System.out.println(set.last());
}
}
output
------
[5, 10, 15, 19, 20]
[5, 10]
[5, 10]
[15, 19, 20]
5
20
NavigableSet
------------
It is child interface of SortedSet.
It provides methods to perform navigation of data.
Introduced in 1.6 version.
Method Summary
--------------
public abstract Object lower(Object);
returns lower element of an object i,e element less than the object.
public abstract Object floor(Object);
returns lower limit of an Object.
public abstract Object ceiling(Object);
returns upper limit of an Object.
public abstract Object higher(Object);
returns an higer element of an object i,e element greater than object.
public abstract Object pollFirst();
returns first element
public abstract Object pollLast();
returns last element.
public abstract java.util.Iterator<E> iterator();
public abstract java.util.NavigableSet<E> descendingSet();
displays elements in descending order.
Program
-------
package com.manohar.java;
import java.util.TreeSet;
public class TreeSetDemo {
public static void main(String[] args) {
TreeSet set=new TreeSet();
set.add(10);
set.add(5);
set.add(20);
set.add(15);
set.add(19);
System.out.println(set);
//methods of navigable set
System.out.println(set.lower(15));//
System.out.println(set.higher(15));//
System.out.println(set.pollFirst());//
System.out.println(set.pollLast());//
System.out.println(set.floor(16));
System.out.println(set.ceiling(18));
System.out.println(set);
//
System.out.println(Math.floor(10.6));//
System.out.println(Math.ceil(5.3));//
}
}
Note1:
If we try to insert heterogenous elements in a TreeSet it leads to ClassCastException.
Note2:
If we add a null value to a TreeSet it leads to NullPointerException.
Note3:
descendingSet() returns elements of set in descending order.
TreeSet set=new TreeSet();
set.add(10);
set.add(5);
set.add(20);
set.add(15);
set.add(19);
System.out.println(set.descendingSet());
Constructor summary of LinkedHashSet and TreeSet
------------------------------------------------
LinkedHashSet()
creates empty HashSet() with initial default capacity 16 and loadfactor 0.75.
LinkedHashSet(Collection)
This accepts any collection as a parameter.
LinkedHashSet(int)
creates empty HashSet with userdefined capacity.
LinkedHashSet(int,float)
creates empty HashSet with userdefined capacity and loadfactor.
TreeSet()
Creates empty tree set, sorted according to the natural ordering of its elements.
TreeSet(Collection<? extends E> c)
Used to copy elements of any other collection into TreeSet.
TreeSet(Comparator<? super E> comparator)
Creates a new empty tree set, and accepts as Comparator as a parameter.
TreeSet(SortedSet<E> s)
Creates a new tree and sorts elements according to SortedSet.
Underlying datastructure of TreeSet is Red-
black trees.
Comparable and Comparator interface
-----------------------------------
Comparable
----------
It is available in java.lang.*
If we want to go natural sorting then we should implement Comparable interface.
It consists of one method compareTo()
signature
---------
public int comparaeTO(object);
How access compareTo()
----------------------
obj1.compareTo(obj2);
case 1:
returns zero if both objects are same.
case2:retuns a negative value of object1 is less than object2 i,e unicode difference.
case3:
retuns a positive value of object1 is greater than object2 i,e unicode difference.
Natural sorting in TreeSet
--------------------------
Every time we add an element to TreeSet,jvm internally call compareTo() method to perform sorting of elements according to natural sorting order.
TreeSet set=new TreeSet();
set.add("A");
set.add("M");//"M".compareTo("A");+ve
set.add("B");//"B".compareTo("M");-ve
// "B".compareTo("A");+ve
System.out.println(set);
obj1-the latest element we add to TreeSet.
obj2-already existing object.
Note:
if -ve exchange of values happens in TreeSet
if +ve no need of any exchange.
Customized sorting int collections
----------------------------------
Comparator
----------
It is an interface available in java.util.* package.
We want to implement customized sorting then we should go for Comparator interface.
It consists of a method compare()
steps for implementing customized sorting in Comparator
------------------------------------------------------
step1:Implement Comparator interface in a class.
accessmodifier class ClassName implements Comparator
{
}
step2:override compare() method and apply comparision logic in Comparator class.
ex:
class MyComparator implements Comparator {
@Override
public int compare(Object obj1, Object obj2) {
String s1 = (String) obj1;
String s2 = (String) obj2;
return -s1.compareTo(s2);
}
}
step3:Create TreeSet object and pass Comparator object as a parameter to the constructor of TreeSet.
ex:
// step1
MyComparator comparator = new MyComparator();
//step2
TreeSet set = new TreeSet(comparator);
Program
-------
package com.manohar.java;
//step1
import java.util.Comparator;
import java.util.TreeSet;
class MyComparator1 implements Comparator
{
@Override
public int compare(Object o1, Object o2) {
String s1=(String)o1;
String s2=(String) o2;
return -s1.compareTo(s2);
}
}
public class ComparatorDemo {
public static void main(String[] args) {
//step2
MyComparator1 comparator1=new MyComparator1();
//step3
TreeSet set=new TreeSet(comparator1);
set.add("samantha");
set.add("deepika");
set.add("priyanka");
set.add("kajal");
set.add("rasi");
System.out.println(set);
}
}
output
------
[samantha, rasi, priyanka, kajal, deepika].
Pojo[Plain old java object]
---------------------------
It is a simple java class with private properties and public setters and getters.
It must have a default constructor.
It must implement a serializable interface.
creating setters and getters
----------------------------
setter methods
--------------
A setter method used to set value a to property of a pojo.
syntax
------
public void setPropertyName(datatype varname)
{
this.varname=varname;
}
getter methods
--------------
A getter method returns a value of a property.
syntax
------
public datatype getPropertyName()
{
return varname;
}
example
-------
class Employee implements Serializable
{
private String empName;
private int empID;
private double empSal;
//
public void setEmpName(String empName)
{
this.empName=empName;
}
public String getEmpName()
{
return empName;
}
}
display details 3 employees
---------------------------
create 3 objects for pojo
set values for all objects using setters.
get values throgh getters.
creating Array of objects
------------------------
Arrays can store both primitives and objects.
Program to create array of objects
----------------------------------
package com.manohar.pojo;
public class Employee {
//property declarations
private String empName;
private int empID;
private double empSal;
//creating setters and getters
}
package com.manohar.java;
import java.util.Scanner;
import com.manohar.pojo.Employee;
public class ArrayOfObjectsDemo {
public static void main(String[] args) {
//declaring array of references
Employee e[] = new Employee[2];//1
//creating objects
for(int i=0;i<e.length;i++){
e[i]=new Employee();//2
}
Scanner scanner = new Scanner(System.in);
// initializing all the objects
for (int i = 0; i < e.length; i++) {
System.out.println("enter name");
e[i].setEmpName(scanner.next());
System.out.println("enter id");
e[i].setEmpID(scanner.nextInt());
System.out.println("enter sal");
e[i].setEmpSal(scanner.nextDouble());
}
// displaying all the objects
for (int i = 0; i < e.length; i++) {
System.out.println(e[i].getEmpName());
System.out.println(e[i].getEmpID());
System.out.println(e[i].getEmpSal());
}
}
}
In the above code @line1 we are declaring Array of reference for Employee.
Whenever we declare an array by default it is initialized with default values.
similarly as Employee is a reference type it is initialized with null as shown in diagram.
Once we declare references we should initialize reference with objects as shown @line2 otherwise it leads to NullPointerException whenever perform operations on these null references.
we are initiazing all the obejcts using setters and getters as shown in loops.
Adding objects to collections and iterating objects from collection
----------
create 5 employee objects,initialize them using setters
add all the five employee objects to ArrayList/HashSet and display values from Employee by iterating collection.
package com.manohar.java;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;
import com.manohar.pojo.Employee;
public class ArrayOfObjectsDemo {
public static void main(String[] args) {
// declaring array of references
Employee e[] = new Employee[2];// line1
// creating objects
for (int i = 0; i < e.length; i++) {
e[i] = new Employee();// line2
}
Scanner scanner = new Scanner(System.in);
// initializing all the objects
for (int i = 0; i < e.length; i++) {
System.out.println("enter name");
e[i].setEmpName(scanner.next());
System.out.println("enter id");
e[i].setEmpID(scanner.nextInt());
System.out.println("enter sal");
e[i].setEmpSal(scanner.nextDouble());
}
ArrayList list = new ArrayList();
for (int i = 0; i < e.length; i++) {
list.add(e[i]);
}
Iterator iterator=list.iterator();
while(iterator.hasNext()){
Employee employee=(Employee) iterator.next();
System.out.println(employee.getEmpID());
System.out.println(employee.getEmpName());
System.out.println(employee.getEmpSal());
}
Iterator iterator2=list.iterator();
while(iterator2.hasNext()){
Employee e1=(Employee) iterator2.next();
System.out.println(e1);
}
}
}
Program
-------
package com.manohar.java;
import java.util.ArrayList;
import java.util.Iterator;
import com.manohar.pojo.Employee;
public class EmployeeTest {
public static void main(String[] args) {
Employee employee1=new Employee();
employee1.setEmpID(1001);
employee1.setEmpName("manohar");
employee1.setEmpSal(10000.00);
Employee employee2=new Employee();
employee2.setEmpID(1002);
employee2.setEmpName("prabhas");
employee2.setEmpSal(20000.00);
Employee employee3=new Employee();
employee3.setEmpID(1003);
employee3.setEmpName("mahesh");
employee3.setEmpSal(30000.00);
Employee employee4=new Employee();
employee4.setEmpID(1004);
employee4.setEmpName("pawan");
employee4.setEmpSal(40000.00);
Employee employee5=new Employee();
employee5.setEmpID(1005);
employee5.setEmpName("balayya");
employee5.setEmpSal(50000.00);
//create collection
ArrayList list=new ArrayList();
list.add(employee1);
list.add(employee2);
list.add(employee3);
list.add(employee4);
list.add(employee5);
Iterator iterator=list.iterator();
while(iterator.hasNext()){
Employee employee=(Employee) iterator.next();
System.out.println(employee.getEmpID());
System.out.println(employee.getEmpName());
System.out.println(employee.getEmpSal());
}
}
}
Sorting Userdefined using TreeSet
---------------------------------
If we want to add objects in TreeSet then the objects must be Comparable otherwise it leads to ClassCastException i,e the class must implement Comparable interface,objects created for such classes are only allowed in TreeSet.
Program
-------
Step1:create an Employee by implementing Comparable interface.
package com.manohar.java;
import java.io.Serializable;
public class Employee implements Serializable, Comparable {
private String name;
private int empID;
private double empSal;
//setters and getters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getEmpID() {
return empID;
}
public void setEmpID(int empID) {
this.empID = empID;
}
public double getEmpSal() {
return empSal;
}
public void setEmpSal(double empSal) {
this.empSal = empSal;
}
@Override
public int compareTo(Object obj) {
Employee employee = (Employee) obj;
if (this.empID < employee.empID) {
return -1;
}
else if (this.empID > employee.empID)
{
return +1;
} else {
return 0;
}
}
}
step2:creating Test class and passing Employee objects TreeSet whihc are sorting according to empid.
public class EmpTest {
public static void main(String[] args) {
Employee employee1 = new Employee();
employee1.setEmpID(1);
Employee employee2 = new Employee();
employee2.setEmpID(2);
Employee employee3 = new Employee();
employee3.setEmpID(3);
TreeSet set = new TreeSet();
set.add(employee1);
set.add(employee3);
set.add(employee2);
for(Object obj:set){
Employee employee=(Employee)obj;
System.out.println(employee.getEmpID());
}
System.out.println(set);
}
}
Customized sorting of userdefined objects
-----------------------------------------
package com.manohar.java;
import java.util.Comparator;
import java.util.TreeSet;
class MyComparator implements Comparator{
@Override
public int compare(Object obj1, Object obj2) {
Employee e1=(Employee)obj1;
Employee e2=(Employee)obj2;
return e2.compareTo(e1);
}
}
public class EmpTest {
public static void main(String[] args) {
Employee employee1 = new Employee();
employee1.setEmpID(1);
Employee employee2 = new Employee();
employee2.setEmpID(2);
Employee employee3 = new Employee();
employee3.setEmpID(3);
TreeSet set = new TreeSet(new MyComparator());
set.add(employee1);
set.add(employee3);
set.add(employee2);
for(Object obj:set){
Employee employee=(Employee)obj;
System.out.println(employee.getEmpID());
}
System.out.println(set);
}
}
write a program to sort employee objects according to employee name----------------------------------------
-------------
Queue[interface]
----------------
A queue inserts elements according to some priority and by default it follows a principle is First in First out[FIFO].
Properties
----------
dynamic
homogenous
insertion order is not preserved
duplicates are allowed
null is not possible in queue.
Method summary
--------------
public abstract boolean add(E);
adds an element to a queue.
public abstract boolean offer(E);
Adds an element to queue.
public abstract Object remove();
remove and retun object,if no element exist in queue throws an exception java.util.NoSuchElementException
public abstract Object poll();
remove and return element,returns null if no element exist in the queue.
public abstract Object element();
return first element,throws exception java.util.NoSuchElementException if no element exist in queue.
public abstract Object peek();
return first element,returns null if no element exist in queue.
PriorityQueue
-------------
It is an impl class of Queue interface.
Introduced in 1.5 version of java.
Program
-------
package com.manohar.java;
import java.util.PriorityQueue;
public class QueueDemo {
public static void main(String[] args) {
PriorityQueue queue=new PriorityQueue();
queue.offer(40);
queue.offer(30);
queue.offer(30);
queue.offer(10);
queue.offer(20);
queue.offer(30);
queue.add(40);
//removal methods
System.out.println(queue.remove());
System.out.println(queue.poll());
//examine elements
System.out.println(queue.element());
System.out.println(queue.peek());
System.out.println(queue);
}
}
Constructor summary
-------------------
PriorityQueue()
Creates a PriorityQueue with the default initial capacity (11) that orders its elements according to their natural ordering.
PriorityQueue(Collection<? extends E> c)
Creates a PriorityQueue containing the elements in the specified collection.
PriorityQueue(int initialCapacity)
Creates a PriorityQueue with the specified initial capacity that orders its elements according to their natural ordering.
PriorityQueue(int initialCapacity, Comparator<? super E> comparator)
Creates a PriorityQueue with the specified initial capacity that orders its elements according to the specified comparator.
PriorityQueue(PriorityQueue<? extends E> c)
Creates a PriorityQueue containing the elements in the specified priority queue.
PriorityQueue(SortedSet<? extends E> c)
Creates a PriorityQueue containing the elements in the specified sorted set.
Program
-------
package com.manohar.java;
import java.util.PriorityQueue;
public class QueueDemo {
public static void main(String[] args) {
PriorityQueue queue = new PriorityQueue();
queue.add(10);
queue.add(20);
queue.add(50);
queue.add(40);
queue.add(70);
queue.add(20);
queue.add(50);
queue.add(40);
queue.offer(100);
System.out.println(queue);
//removal of elemements
System.out.println(queue.remove());
System.out.println(queue.poll());
//examining elements
System.out.println(queue.element());
System.out.println(queue.peek());
System.out.println(queue);
}
}
Dequeue[double ended queue]
---------------------------
A deque is used to pefrom insert and delete operations from bothe the ends i,e rear and front end.Generally in a queue insertion is done through rear,deletion through front.
It is intorduced in 1.6 version.
It is a child interface of Queue
Method summary
--------------
//addition if elements to dequeue
public void addFirst(E);
public void addLast(E);
public boolean offerFirst(E);
public boolean offerLast(E);
//removal of elements from dequeue
public Object removeFirst();
public Object removeLast();
public Object pollFirst();
public Object pollLast();
public boolean removeFirstOccurrence(java.lang.Object);
public boolean removeLastOccurrence(java.lang.Object);
//examining the elements of queue
public abstract E getFirst();
public abstract E getLast();
public abstract E peekFirst();
public abstract E peekLast();
Implementation classes
----------------------
A Deque has the following implementation classes.
1)ArrayDeque.
2)ConcurrentLinkedDeque.
3)LinkedBlockingDeque.
4)LinkedList.
Program
-------
package com.manohar.java;
import java.util.LinkedList;
public class QueueTest {
public static void main(String[] args) {
LinkedList list=new LinkedList();
//addition of elements to dequeu
list.add(10);
list.add(20);
list.add(30);
list.addFirst(40);
list.addLast(50);
list.add(10);
list.offerFirst(60);
list.offerLast(70);
list.add(10);
System.out.println(list);
//removal
list.removeFirstOccurrence(10);
System.out.println(list);
list.removeLastOccurrence(10);
list.removeLast();
System.out.println(list);
list.removeFirst();
System.out.println(list);
list.pollFirst();
System.out.println(list);
list.pollLast();
System.out.println(list);
//examine
System.out.println(list.getFirst());
System.out.println(list.getLast());
System.out.println(list.peekFirst());
System.out.println(list.peekLast());
}
}
output
------
[60, 40, 10, 20, 30, 50, 10, 70, 10]
[60, 40, 20, 30, 50, 10, 70, 10]
[60, 40, 20, 30, 50, 10]
[40, 20, 30, 50, 10]
[20, 30, 50, 10]
[20, 30, 50]
20
50
20
50
Map
---
Map is an interface available in java.util.* package.
Map is represents objects in the form of
key-value pairs.
ex:
1--manohar
2--raghu
3--shekar
4--kvr
1--manohar
keys must be unique.
values can be duplicated.
Each key-value pair is called one entry.
-----
Map Heirarchy
-------------
Map
|
----------------------------------------------
^ | ^ ^ ^
| | | | |
HahsMap| LinkedHashMap IdentityHashMap SortedMap.
| ^
WeakHashMap |
NavigableMap.
^
|
TreeMap.
Note:Map and Collection are different heirachies.
Map is root interface of all Map's in java.
It is dynamic
It is used to represent group objects in the form of key and value pairs.
Methods of Map inteface
-----------------------
public int size();
returns size of Map.
public boolean isEmpty();
checks whether Map is empty or not.
public boolean containsKey(java.lang.Object);
checks whether a key is available in a map or not
returns true if available otherwise false.
public boolean containsValue(java.lang.Object);
checks whether a value is available in a map or not
returns true if available otherwise false.
public Object get(java.lang.Object);
returns a value of a key.
public Object put(K, V);
adds an entry to a Map.
public Object remove(java.lang.Object);
remove an object from a Map.
public void putAll(java.util.Map<? extends K, ? extends V>);
Add one Map to another Map.
public void clear();
clears a Map.
public java.util.Set<K> keySet();
returns Set of keys.
public java.util.Collection<V> values();
returns collection values
public java.util.Set<java.util.Map$Entry<K, V>> entrySet();
returns all entries in the form of Set.
public boolean equals(java.lang.Object);'
public int hashCode();
public Object getOrDefault(java.lang.Object, V);
returns a value of a key if it exists in a map otherwise returns default value specified by developer.
public boolean remove(java.lang.Object,
java.lang.Object);
public boolean replace(K, V, V);
public Object replace(K, V);
Map.Entry
---------
Entry is a inner interface of a Map.
A Map interface HAS-A Entry interface.
Entry provides methods to operate on an entry,it provides methods to read and update an entry in a Map.
syntax
------
interface Map
{
interface Entry
{
public K getKey();
//returns from entry
public V getValue();
//return value from entry
public V setValue(V);
//updates a value in entry
public boolean equals(java.lang.Object);
public int hashCode();
}
}
HashMap
-------
It is impl class of Map.
Introduced in 1.2 version of java.
Properties
----------
dynamic
Both keys and values are heterogenous.
Insertion order is not preserved because,objects are inserted into a Map based on HashCode of a keys.
keys must be unique,values can be duplicated.
null insertion is possible for both keys and values,but for keys null insertion is allowed only for one time.
underlying datastructure is Hashtable.
Constructor summary
-------------------
HashMap()
Creates an empty HashMap with the default initial capacity (16) and the default load factor (0.75).
HashMap(int initialCapacity)
Creates an empty HashMap with the specified initial capacity and the default load factor (0.75).
HashMap(int initialCapacity, float loadFactor)
Creates an empty HashMap with the specified initial capacity and load factor.
HashMap(Map<? extends K,? extends V> m)
Creates a new HashMap with the same mappings as the specified Map.
Program
-------
package com.manohar.java;
public class HashMapDemo {
public static void main(String[] args) {
HashMap map=new HashMap();
map.put(1,"manohar");
map.put(2, "manohar");
map.put(3, "manohar");
map.put(4, "kvr");
map.put(5, "venkatesh");
map.put(null,"sunil");
map.put(1,"sachin");
System.out.println(map);
System.out.println(map.size());//6
System.out.println(map.isEmpty());//false
System.out.println(map.containsKey(7));
System.out.println(map.containsValue("manohar"));
System.out.println(map.get(1));
System.out.println(map.remove(null));
System.out.println(map);
Set set=map.keySet();
System.out.println(set);
Collection collection=map.values();
System.out.println(collection);
System.out.println(map.getOrDefault(4,"xyz"));
System.out.println(map.replace(4,"kvr","manohar"));
System.out.println(map.replace(1,"virat"));
System.out.println(map);
}
}
Program
-------
package com.manohar.java;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
public class HashMapDemo {
public static void main(String[] args) {
HashMap map=new HashMap();
map.put(10,"orange");
map.put(2, "grapes");
map.put(3, "apple");
map.put(40, "pineapple");
map.put(5, "mango");
Set set=map.keySet();
Iterator iterator=set.iterator();
while(iterator.hasNext()){
int x=(int)iterator.next();
System.out.println(x+" "+map.get(x));
}
System.out.println(map);
}
}
Program
-------
package com.manohar.java;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
public class HashMapDemo1 {
public static void main(String[] args) {
HashMap map = new HashMap();
map.put(1, "manohar");
map.put(2, "raghu");
map.put(3, "shekar");
map.put(4, "kvr");
map.put(5, "manohar");
System.out.println(map);
Collection collection=map.values();
Set set=new HashSet(collection);
System.out.println(set);
}
}
Dictionary
^
|
Hashtable
^
|
Properties
Dictionary
----------
It is used to represent data in the form of key and value pairs.
It is a legacy class introduced in 1.0 version.
It is an abstract class.
Hashtable
---------
It is a child of Dictionary and impl class of Map.
1.0 version.
Properties
----------
dynamic.
Insertion order is not preserved.
null values are not allowed for both keys and values.
keys must be unique,values can be duplicated.
both keys and values can be heterogenous.
underlying datatstructure Hashtable.
It is a synchronized class.
It is threadsafe
Performance wise it is poor.
constructor summary
-------------------
Hashtable()
Creates a new, empty hashtable with a default initial capacity (11) and load factor (0.75).
Hashtable(int initialCapacity)
Creates a new, empty hashtable with the specified initial capacity and default load factor (0.75).
Hashtable(int initialCapacity, float loadFactor)
Creates a new, empty hashtable with the specified initial capacity and the specified load factor.
Hashtable(Map<? extends K,? extends V> t)
Creates a new hashtable with the same mappings as the given Map.
Program
-------
package com.manohar.java;
import java.util.Hashtable;
public class HashTableDemo {
public static void main(String[] args) {
Hashtable hashtable=new Hashtable();
hashtable.put(1,"samsung");
hashtable.put(2,"iphone");
hashtable.put("a",1);
hashtable.put(3,"nokia");
hashtable.put(4,"lg");
hashtable.put(5,"lenovo");
System.out.println(hashtable);
}
}
}
Properties
----------
A properties class is used to perform operations on a properties file like read,write,update and delete operations.
A properties file is used to represent properties like database connection,language,location etc
Program
-------
package com.manohar.java;
import java.util.Hashtable;
import java.util.Properties;
public class HashTableDemo {
public static void main(String[] args) {
Properties properties=new Properties();
properties.put(1,"rambo");
properties.put(2,"terminator");
properties.put(3,"matrix");
properties.put(4,"avengers");
properties.put(5,"expendables");
System.out.println(properties);
}
}
putAll()
--------
This is used to copy all the entries of one map to another map.
Program
-------
package com.manohar.java;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Properties;
public class HashTableDemo {
public static void main(String[] args) {
Properties properties=new Properties();
properties.put(1,"rambo");
properties.put(2,"terminator");
properties.put(3,"matrix");
properties.put(4,"avengers");
properties.put(5,"expendables");
System.out.println(properties);
HashMap map=new HashMap();
map.putAll(properties);
System.out.println(map);
}
}
Collection
----------
addAll()
Adds one collection to another collection.
removeAll()
remove one collection from another collection.
retainAll()
retains(keeps) common elements between 2 collections and removes uncommon elements of a collection.
containsAll()
checks whether one collection exists in another collection or not
Program
-------
package com.manohar.java;
import java.util.ArrayList;
public class MethodsDemo {
public static void main(String[] args) {
ArrayList list=new ArrayList();
list.add("dog");
list.add("cat");
list.add("tiger");
ArrayList list1=new ArrayList();
list1.add("rose");
list1.add("lilly");
list1.add("jasmine");
ArrayList list2=new ArrayList();
list2.add("rose");
list2.add("lilly");
list2.add("jasmine");
list2.add("sunflower");
list2.add("cauliflower");
list2.retainAll(list1);
System.out.println(list2);
list2.addAll(list);
System.out.println(list2);
System.out.println(list2.containsAll(list));
list2.removeAll(list);
System.out.println(list2.containsAll(list));
System.out.println(list2);
}
}
Utility classes in Collection
-----------------------------
we have 2 utility classes in java.util.* package
i)Collections
ii)Arrays
Collections
-----------
Collections is a class which provides methods to perform operations on collections like sorting,searching,reversing etc.
Method summary
--------------
public static void sort(List list);
public static void sort(List list, Comparator c).
public static int binarySearch(List list,Object key).
public static void copy(List dest,List src);.
public static Object max(Collection coll).
public static Object min(Collection coll).
public static void reverse(List list).
public static Comparator reverseOrder(Comparator).
Program
-------
package com.manohar.java;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class CollectionsDemo {
public static void main(String[] args) {
List list = new ArrayList(10);
list.add(10);
list.add(20);
list.add(5);
list.add(15);
list.add(9);
System.out.println(list);
List list2 = new ArrayList();
list2.add(50);
list2.add(60);
list2.add(70);
list2.add(50);
list2.add(60);
list2.add(70);
Collections.copy(list2, list);
System.out.println(list2);
Collections.sort(list2, Collections.reverseOrder());
System.out.println(list2);
Collections.sort(list);
System.out.println(list);
int key = 45;
int res = Collections.binarySearch(list, key);
System.out.println(res);
Collections.reverse(list);
System.out.println(list);
System.out.println(Collections.max(list));
System.out.println(Collections.min(list));
}
}
Note:if we are using copy method make sure the size of destination list is having bigger capacity than source list.
Note2:reverseOrder() method should be passed as a parameter to sort() method,sort() method will sort elements of List in ascending order,reverseOrder() will convert this ascending to descending.
Note3:while applying binary search make sure a List is sorted in ascending order.
Arrays
------
Arrays is an utilty class applicable in primitive arrays to perform sorting,searching etc.
public static void sort(array);
public static int binarySearch(array,key);
public boolean equals(array1,array2);
Program
-------
package com.manohar.java;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class CollectionsDemo {
public static void main(String[] args) {
String s[] = { "samantha", "kajal", "rakul", "suresh", "rashi" };
String s2[] = { "samantha", "kajal", "rakul", "suresh", "rashi" };
System.out.println(Arrays.equals(s, s2));
for (String str : s)
System.out.print(str + ",");
System.out.println();
Arrays.sort(s);
for (String str : s)
System.out.println(str + ",");
int res = Arrays.binarySearch(s, "suresh");
System.out.println(res);
List list=Arrays.asList(s);
System.out.println(list);
}
}
converting collection to array
------------------------------
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Hashtable;
import java.util.List;
public class MapDemo {
public static void main(String[] args) {
ArrayList l=new ArrayList();
l.add(10);
l.add(20);
l.add(30);
l.add(40);
l.add(50);
int a[]=new int[l.size()];
Object obj[]=l.toArray();
for(int i=0;i<obj.length;i++){
a[i]=(int)obj[i];
}
for(int i:a){
System.out.println(i);
}
}
}
Note:
asList() method converts array to List.
public class MapDemo {
public static void main(String[] args) {
String s[]={"inki","pinki","ponky"};
List list=Arrays.asList(s);
System.out.println(list);
}
}
Methods to synchronize List,Set,Map
-----------------------------------
To get synchornized version of List,Set,Map,Collections class provides following methods.
i) public List synchronizedList()
returns synchronizedList of any List class.
ii)public Set synchronizedSet()
returns synchronizedSet of any Set class.
iii)public Map synchronizedMap()
returns synchronizedMap of any Map class.
ArrayList l=new ArrayList();
l.add(10);
l.add(20);
l.add(30);
List list=Collections.synchronizedList(l);
simliary Apply for Set and Map
Generics
--------
Collections are heterogenous
We should always apply casting.
code:
ArrayList list=new ArrayList();
list.add(10);
list.add(20);
int x=(int)list.get(0);
get() returns object,if we don't apply casting properly then it may lead to ClassCastException.
Collection is not type safe.
Generic Collection
-------------------
generics provide type safety.
type casting is not necessary.
generics provides compiletime checking.
Generic respresentation of collection
-------------------------------------
We declare a generic representation by using diamond(<>) operator with collection.
syntax
------
ClassName<type> referencename=new ClassName<type>();
we should pass type as only reference type as a parameter to a generic collection,primitive are not accepted as a parameter.
Program
-------
public class GenDemo {
public static void main(String[] args) {
ArrayList<Integer> list=new ArrayList<Integer>();
list.add(10);
list.add(20);
list.add(30);
list.add(40);
list.add(50);
int x=list.get(0);//line1
System.out.println(x);
System.out.println(list);
}
}
In the above code we are getting value from ArrayList @line1 without applying any casting.
Generic respresentation of a Map
--------------------------------
ClassName<tyep1,type2> referencename=new ClassName<type1,type>();
Here we should represent type1 and type2 as class type or reference type.
Program
-------
public class GenDemo {
public static void main(String[] args) {
HashMap<Integer,String> map=new HashMap<Integer,String>();
map.put(1,"manohar");
map.put(2,"venkatesh");
map.put(3, "raghu");
map.put(4, "shekar");
map.put(5, "kvr");
System.out.println(map);
}
}
creating userdefined Generic class
----------------------------------
we should declare by using diamond operator with a classname shown in below.
syntax
------
accessmodifier class ClassName<E>
{
}
Here E is a generic type paramater which accepts any type of value like Integer,Float,Double,ClassType like Employee,Donkey,Monkey etc
we use the following standard names for parameter types
T - Type
E - Element
K - Key
N - Number
V - Value
Program
-------
class Test<T>
{
T a;
public void add(T a){
this.a=a;
}
public T get(){
return a;
}
}
public class GenDemo {
public static void main(String[] args) {
Test<Integer> t1=new Test<Integer>();
t1.add(10);
System.out.println(t1.get());
Test<String> t2=new Test<String>();
t2.add("how is it");
System.out.println(t2.get());
}
}
creating generic method
-----------------------
A generic method will any type of value.The parameter to a generic methods must be of generic type as shown below.
syntax
------
accessmodifier <T> returntype methidname(T t)
{
}
Program
-------
public class GenDemo {
public <T> void display(T t[]){
for(T t1:t){
System.out.println(t1);
}
}
public static void main(String[] args) {
Integer a[]={1,2,3,4,5};
new GenDemo().display(a);
}
}
Wild card characters in gererics
--------------------------------
Special symbols used with Collections are called Wild card charcaters.
? is the wild card character applied with collections.
In generic code, the question mark (?), called the wildcard, represents an unknown type
syntax
------
<? extends ClassName>
Subscribe to:
Comments (Atom)