Collections and Generics PDF
Collections and Generics PDF
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96
96 96 96, 9246212143 | www.durgasoft.com Page 1
JAVA Means DURGASOFT
Collectionsframework (java.util)
Pre-requisite topics for Collections framework:-
1) AutoBoxing.
2) toString() method.
3) type-casting.
4) interfaces.
5) for-each loop.
6) implementation classes.
7) compareTo() method.
8) Wrapper classes.
9) Marker interfaces advantages.
10) Anonymous inner classes.
Collection frame contains group of classes and interfaces by using these classes & interfaces we
are representing group of objects as a single entity.
Collection is sometimes called a container. And it is object that groups multiple elements into a
single unit.
Collections are used to store, retrieve ,manipulate data.
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96
96 96 96, 9246212143 | www.durgasoft.com Page 2
JAVA Means DURGASOFT
Note :- The root interface of Collection framework is Collection it contains 15 methods so all
implementation classes are able to use that methods.
public abstract int size();
public abstract boolean isEmpty();
public abstract boolean contains(java.lang.Object);
public abstract java/util/Iterator<E> iterator();
public abstract java.lang.Object[] toArray();
public abstract <T extends java/lang/Object> T[] toArray(T[]);
public abstract boolean add(E);
public abstract boolean remove(java.lang.Object);
public abstract boolean containsAll(java/util/Collection<?>);
public abstract boolean addAll(java/util/Collection<? extends E>);
public abstract boolean removeAll(java/util/Collection<?>);
public abstract boolean retainAll(java/util/Collection<?>);
public abstract void clear();
public abstract boolean equals(java.lang.Object);
public abstract int hashCode();
The interface contains abstract method and for that interfaces object creation is not
possible hence think about implementation classes of that interfaces.
Collection vs Collections:-
Collection is interface it is used to represent group of objects as a single entity.
Collections is utility class it contains methods to perform operations.
Characteristics of Collection frame work classes:-
1) The collect ion framework classes are introduced in different Versions.
2) Heterogeneous data allowed or not allowed.
All classes allowed heterogeneous data except two classes
i. TreeSet ii. TreeMap
3) Null insertion is possible or not possible.
4) Insertion order is preserved or not preserved.
Input --->e1 e2 e3 output --->e1 e2 e3 insertion order is preserved
Input --->e1 e2 e3 output --->e2 e1 e3 insertion order is not-preserved
5) Collection classes’ methods are synchronized or non-synchronized.
6) Duplicate objects are allowed or not allowed.
add(e1)
add(e1)
7) Collections classes underlying data structures.
8) Collections classes supported cursors.
extends
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96
96 96 96, 9246212143 | www.durgasoft.com Page 3
JAVA Means DURGASOFT
Stack(c)
1.0 version
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96
96 96 96, 9246212143 | www.durgasoft.com Page 4
JAVA Means DURGASOFT
Java.util.ArrayList:-
ArrayList is implementing List interface it widely used class in projects because it is providing
functionality and flexibility
To check parent class and interface use below command.
D:\ratan>javap java.util.ArrayList
public class java.util.ArrayList<E>
extends java.util.AbstractList<E>
implements java.util.List<E>,
java.util.RandomAccess,
java.lang.Cloneable,
java.io.Serializable
ArrayList Characteristics:-
1) ArrayList Introduced in 1.2 version.
2) ArrayList stores Heterogeneous objects(different types).
3) Inside ArrayList we can insert Null objects.
4) ArrayList preserved Insertion order it means whatever the order we inserted the data in the same
way output is printed.
a. Input -e1 e2 e3 output -e1 e2 e3 insertion order is preserved
b. Input --e1 e2 e3 output --e1 e3 e2 insertion order is not- preserved
5) ArrayList methods are non-synchronized methods.
6) Duplicate objects are allowed.
7) The under laying data structure is growable array.
8) By using cursor we are able to retrieve the data from ArrayList : Iterator , ListIterator
ArrayList Capacity:-
import java.util.*;
import java.lang.reflect.Field;
class Test
{ public static void main(String[] args)throws Exception
{ ArrayList<Integer> al = new ArrayList<Integer>(5);
for (int i=0;i<10 ;i++)
{ al.add(i);
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96
96 96 96, 9246212143 | www.durgasoft.com Page 5
JAVA Means DURGASOFT
System.out.println("size="+al.size()+" capacity="+getcapacity(al));
}
}
static int getcapacity(ArrayList l)throws Exception
{ Field f = ArrayList.class.getDeclaredField("elementData");
f.setAccessible(true);
return ((Object[])f.get(l)).length;
}
}
D:\>java Test
size=1 capacity=5
size=2 capacity=5
size=3 capacity=5
size=4 capacity=5
size=5 capacity=5
size=6 capacity=8
size=7 capacity=8
size=8 capacity=8
size=9 capacity=13
size=10 capacity=13
Example :-Collections vs Autoboxing
upto 1.4 version by using wrapper classes, create objects then add that objects in ArrayList.
import java.util.ArrayList;
class Test
{ public static void main(String[] args)
{ ArrayList al = new ArrayList();
Integer i = new Integer(10); //creation of Integer Object
Character ch = new Character('c'); //creation of Character Object
Double d = new Double(10.5); //creation of Double Object
//adding wrapper objects into ArrayList
al.add(i);
al.add(ch);
al.add(d);
System.out.println(al);
}
}
But from 1.5 version onwards autoboxing concept is introduced so add the primitive value directly that is
automatically converted into wrapper objects format.
import java.util.ArrayList;
class Test
{ public static void main(String[] args)
{ ArrayList al = new ArrayList();
al.add(10); //primitive int value --->Integer Object conversion //AutoBoxing
al.add('a'); //primitive char value --->Integer Object conversion //AutoBoxing
al.add(10.5); //primitive double value --->Integer Object conversion //AutoBoxing
System.out.println(al);
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96
96 96 96, 9246212143 | www.durgasoft.com Page 6
JAVA Means DURGASOFT
}
}
In above example when we are adding primitive char value al.add(‘c’) in ArrayList that value is
automatically converted Character object format because ArrayList is able to store objects that
is called AutoBoxing.
When we print the ArrayList data for every object internally it is calling toString() method.
Example :- in Collection framework when we remove the data by using numeric value that is by
default treated as a index value.
ArrayList al = new ArrayList();
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96
96 96 96, 9246212143 | www.durgasoft.com Page 7
JAVA Means DURGASOFT
al.add(10);
al.add("ratan");
al.add('a');
System.out.println(al);
In above example if u want remove 10object by using object name then we are using below code.
al.remove(10);
But whenever we are writing above code then JVM treats that 10 is index value hence it is generating
exception java.lang.IndexOutOfBoundsException: Index: 10, Size: 3
To overcome above limitation if we want remove 10 Integer object then use below code.
ArrayList al = new ArrayList();
Integer i = new Integer(10);
al.add(i);
al.remove(i);
System.out.println(al);
import java.util.ArrayList;
class Test
{ public static void main(String[] args)
{ Emp e1 = new Emp(111,"ratan");
Student s1 = new Student(222,"xxx");
ArrayList al = new ArrayList();
al.add(10); //toString() --->it execute Integer class toString()
al.add('a'); //toString() --->it execute Character class toString()
al.add(e1); //toString() --->it executes Object class toString()
al.add(s1); //toString() --->it executes Object class toString()
System.out.println(al.toString());//[10, a, Emp@d70d7a, Student@b5f53a]
for (Object o : al)
{ if (o instanceof Integer)
System.out.println(o.toString());
if (o instanceof Character)
System.out.println(o.toString());
if (o instanceof Emp){
Emp e = (Emp)o;
System.out.println(e.eid+"---"+e.ename);
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96
96 96 96, 9246212143 | www.durgasoft.com Page 8
JAVA Means DURGASOFT
}
if (o instanceof Student){
Student s = (Student)o;
System.out.println(s.sid+"---"+s.sname);
}
}
}
}
import java.util.ArrayList;
class ArrayListDemo
{ public static void main(String[] args)
{ ArrayList<String> al = new ArrayList<String>();
al.add("anu");
al.add("Sravya");
System.out.println(al);
}
}
Case 4:-
ArrayList<Type> obj = new ArrayList<Type>(Collections.nCopies(count, object));
import java.util.*;
class ArrayListDemo
{ public static void main(String[] args)
{ Emp e1 = new Emp(111,"ratan");
ArrayList<Emp> al = new ArrayList<Emp>(Collections.nCopies(5,e1));
for (Emp e:al)
{ System.out.println(e.ename+"---"+e.eid);
}
}
}
Case 5:-adding Objects into ArrayList by using addAll() method of Collections class.
import java.util.*;
class Test
{ public static void main(String[] args)
{ ArrayList<String> al = new ArrayList<String>();
String[] strArray={"ratan","anu","Sravya"};
Collections.addAll(al,strArray);
System.out.println(al);
}
}
Note :-
in java it is recommended to use generic version of collections class to store specified type of data.
Syntax:-
ArrayList<type-name> al = new ArrayList<type-name>();
Examples:-
ArrayList<Integer> al = new ArrayList<Integer>(); //store only Integer objects
ArrayList<String> al = new ArrayList<String>(); //store only String objects
ArrayList<Student> al = new ArrayList<Student>(); //store only Student objects
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96
96 96 96, 9246212143 | www.durgasoft.com Page 10
JAVA Means DURGASOFT
2) Always check the type of the object by 2) Type checking is not required because it
using instanceof operator. contains only one type of data.
4) If we are using normal version while 4) If we are using generic version compiler
compilation compiler generate worning won’t generate worning messages.
message likeunchecked or unsafe
operations.
Example:- normal version of ArrayList holding Example :- generic version of ArrayList
different types of Objects. holding only Integer data.
import java.util.*; import java.util.*;
class Test class Test
{ public static void main(String[] args) { public static void main(String[] args)
{ ArrayList al = new ArrayList(); {ArrayList<Integer> al = new ArrayList<Integer>();
al.add(10); al.add(10);
al.add('a'); al.add(20);
al.add(10.4); al.add(30);
al.add(true); al.add(40);
System.out.println(al); System.out.println(al);
} }
} }
{ System.out.println(e.eid+"---"+e.ename);
}
}
}
//java.lang.IndexOutOfBoundsException: toIndex = 7
//ArrayList<String> a4 = new ArrayList<String>(a1.subList(1,7));
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96
96 96 96, 9246212143 | www.durgasoft.com Page 12
JAVA Means DURGASOFT
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96
96 96 96, 9246212143 | www.durgasoft.com Page 13
JAVA Means DURGASOFT
al.add("anu");
al.add("Sravya");
al.add("ratan");
al.add("natraj");
String[] a = new String[al.size()];
al.toArray(a);
//normal approach to print the data
System.out.println(a[0]);
System.out.println(a[1]);
System.out.println(a[2]);
System.out.println(a[3]);
//for-each loop to print the data
for (String s:a)
{System.out.println(s);
}
}
}
Example :- conversion of ArrayList to Array
public abstract java.lang.Object[] toArray();
import java.util.*;
class Test
{ public static void main(String[] args)
{ ArrayList al = new ArrayList();
al.add(10);
al.add('c');
al.add("ratan");
//converison of ArrayList to array
Object[] o = al.toArray();
for (Object oo :o)
{ System.out.println(oo);
}
}
}
Example :-
import java.util.*;
class Test
{ public static void main(String[] args)
{ ArrayList al = new ArrayList();
al.add(new Emp(111,"ratan"));
al.add(new Student(1,"xxx"));
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96
96 96 96, 9246212143 | www.durgasoft.com Page 14
JAVA Means DURGASOFT
al.add("ratan");
//converison of ArrayList to array
Object[] o = al.toArray();
for (Object oo :o)
{ if (oo instanceof Emp)
{ Emp e = (Emp)oo;
System.out.println(e.eid+"---"+e.ename);
}
if (oo instanceof Student)
{ Student s = (Student)oo;
System.out.println(s.sid+"---"+s.sname);
}
if (oo instanceof String)
{ System.out.println(oo.toString());
}
}
}
}
1. Enumaration
2. Iterator
3. ListIteator
import java.util.*;
class Test
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96
96 96 96, 9246212143 | www.durgasoft.com Page 16
JAVA Means DURGASOFT
}
}
Comparable vs Comparator :-
Note :- it is possible to sort String and all wrapper objects because these objects are
implementing Cloneable interface.
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96
96 96 96, 9246212143 | www.durgasoft.com Page 17
JAVA Means DURGASOFT
If we want to sort user defined class Emp based on eid or ename then your class must
implements Comparable interface.
Comparable present in java.lang package it contains only one method compareTo(obj)
public abstract int compareTo(T);
If your class is implementing Comparable interface then that objects are sorted
automatically by using Collections.sort()And the objects are sorted by using
compareTo() method of that class.
By using comparable it is possible to sort the objects by using only one instance
variable either eid or ename.
Emp.java:-
class Emp implements Comparable
{ int eid;
String ename;
Emp(int eid,String ename)
{ this.eid=eid;
this.ename=ename;
}
/* it is sorting the data by using enameinstance variable
public int compareTo(Object o)
{ Emp e = (Emp)o;
return ename.compareTo(e.ename);
}
*/
public int compareTo(Object o)
{ Emp e = (Emp)o;
if (eid == e.eid )
{ return 0; }
else if (eid > e.eid)
{ return 1; }
else
{ return -1; }
}
}
Another format:-
class Emp implements Comparable<Emp>
{ ***********
public int compareTo(Emp e)
{ ***********
}
}
Test.java:-
import java.util.*;
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96
96 96 96, 9246212143 | www.durgasoft.com Page 18
JAVA Means DURGASOFT
class Test
{ public static void main(String[] args)
{ ArrayList al = new ArrayList();
al.add(new Emp(333,"ratan"));
al.add(new Emp(222,"anu"));
al.add(new Emp(111,"Sravya"));
Collections.sort(al);
Iterator itr = al.iterator();
while (itr.hasNext())
{ Emp e = (Emp)itr.next();
System.out.println(e.eid+"---"+e.ename);
}
}
}
Java.utilComparator :-
The class whose objects are stored do not implements this interface some third party
class can also implements this interface.
Comparable present in java.langpackage but Comparator present in java.util package.
Comparator interface contains two methods,
public interface java.util.Comparator<T> {
public abstract int compare(T, T);
public abstract boolean equals(java.lang.Object);
}
Emp.java:-
class Emp
{ int eid;
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96
96 96 96, 9246212143 | www.durgasoft.com Page 19
JAVA Means DURGASOFT
String ename;
Emp(int eid,String ename)
{ this.eid=eid;
this.ename=ename;
}
}
EidComp.java:-
import java.util.Comparator;
class EidComp implements Comparator
{ public int compare(Object o1,Object o2)
{ Emp e1 = (Emp)o1;
Emp e2 = (Emp)o2;
if (e1.eid==e2.eid)
{ return 0; }
else if (e1.eid>e2.eid)
{ return 1; }
else
{ return -1; }
}
}
EnameComp.java:-
import java.util.Comparator;
class EnameComp implements Comparator
{ public int compare(Object o1,Object o2)
{ Emp e1 = (Emp)o1;
Emp e2 = (Emp)o2;
return (e1.ename).compareTo(e2.ename);
//return -(e1.ename).compareTo(e2.ename); //print data descending order
}
}
Test.java:-
import java.util.*;
class Test
{ public static void main(String[] args)
{ ArrayList<Emp> al = new ArrayList<Emp>();
al.add(new Emp(333,"ratan"));
al.add(new Emp(222,"anu"));
al.add(new Emp(111,"Sravya"));
al.add(new Emp(444,"xxx"));
System.out.println("sorting by eid");
Collections.sort(al,new EidComp());
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96
96 96 96, 9246212143 | www.durgasoft.com Page 20
JAVA Means DURGASOFT
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96
96 96 96, 9246212143 | www.durgasoft.com Page 21
JAVA Means DURGASOFT
3. Method calling to
perform sorting
2. Sorting method
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96
96 96 96, 9246212143 | www.durgasoft.com Page 22
JAVA Means DURGASOFT
al.add("30");
Vector<String> v = new Vector<String>();
v.add("ten");
v.add("twenty");
//copy data from vector to ArrayList
Collections.copy(al,v);
System.out.println(al);
}
}
D:\vikram>java Test
[ten, twenty, 30]
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96
96 96 96, 9246212143 | www.durgasoft.com Page 24
JAVA Means DURGASOFT
Enumaration:-0
1. Enumeration cursor introduced in 1.0 version hence it is called legacy cursor.
2. Enumeration is a legacy cursor it is used to retrieve the objects form only legacy classes (vector,
Stack, HashTable…)hence it is not a universal cursor.
3. to retrieve Object from collection classes Enumeration Object uses two methods.
public abstract boolean hasMoreElements();
This method is used to check whether the collection class contains Objects or not, if
collection class contains objects return true otherwise false.
public abstract E nextElement();
This method used to retrieve the objects from collection classes.
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96
96 96 96, 9246212143 | www.durgasoft.com Page 25
JAVA Means DURGASOFT
6. By using this cursor it is possible to read the data only, it not possible to update the data an not
possible to remove the data.
7. By using this cursor we are able to retrieve the data only in forward direction.
Iterator:-
1) Iterator cursor introduced in 1.2 versions.
4) The Iterator object uses three methods to retrieve the objects from collections classes.
public abstract boolean hasNext();
This is used to check whether the Objects are available in collection class or not ,
if available returns true otherwise false.
public abstract E next();
This method used to retrieve the objects.
public abstract void remove();
This method is used to remove the objects from collections classes.
6) By using Iterator cursor we are able to perform read and remove operations but it is not
possible to perform update operation.
7) By using Iterator we are able to read the data only in forward direction.
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96
96 96 96, 9246212143 | www.durgasoft.com Page 26
JAVA Means DURGASOFT
2. Legacy or not
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96
96 96 96, 9246212143 | www.durgasoft.com Page 27
JAVA Means DURGASOFT
9) Interface
Enumeration
1) Used to retrieve the data from
collection classes.
LIstIterator:-
1. ListIterator cursor Introduced in 1.2 version
2. This cursor is applicable only for List type of classes(ArrayList,LinkedList,Vector,Stack...etc) hence
it is not a universal cursor.
3. listIterator() method used to get ListIterator object
ex:- LinkedList ll = new LinkedList();
ll.add(10);
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96
96 96 96, 9246212143 | www.durgasoft.com Page 28
JAVA Means DURGASOFT
ll.add(20);
ll.add(30);
ListIterator lstr = ll.listIterator();
4. ListIterator contains fallowing methods
public abstract boolean hasNext();---->to check the Objects
public abstract E next(); ----->to retrieve the objects top to bottom
public abstract boolean hasPrevious(); ---check the objects in previous direction
public abstract E previous(); ---->to retrieve the Objects from previous direction
public abstract int nextIndex();---->to get index
public abstract int previousIndex();--->to get the index from previous direction.
public abstract void remove(); --->to remove the Objects
public abstract void set(E); ----->to replace the particular Object
public abstract void add(E);---->to add new Objects
5. By using this cursor we are able to read & remove & update the data.
6. By using this cursor we are able to read the data both in forward and backward direction.
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96
96 96 96, 9246212143 | www.durgasoft.com Page 30
JAVA Means DURGASOFT
import java.util.*;
class Test
{ public static void main(String[] args)
{ Vector v = new Vector();
v.addElement(10);
v.addElement(20);
v.addElement(30);
//it returns implementation class object of Enumeration interface
Enumeration e = v.elements();
System.out.println(e.getClass().getName());
2) By using cursors.
3) By using get() method.
Example application:-
import java.util.*;
class Test
{ public static void main(String[] args)
{ //ArrayList able to store only String Objects
ArrayList<String> al =new ArrayList<String>();
al.add("A");
al.add("B");
al.add("C");
al.add("D");
al.add(null);
//1st appraoch to print Collection class elements (by using for-each loop)
for (String a : al)
{ System.out.println(a); }
Example:-
import java.util.*;
class Emp
{ //instance variables
int eid;
String ename;
Emp(int eid ,String ename) //local variables
{ //conversion of local variables to instance variables
this.eid = eid;
this.ename = ename;
}
public static void main(String[] args)
{ Emp main1 = new Emp(111,"ratan");
Emp main2 = new Emp(222,"Sravya");
Emp main3 = new Emp(333,"aruna");
Emp sub1 = new Emp(444,"anu");
Emp sub2 = new Emp(555,"banu");
}
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96
96 96 96, 9246212143 | www.durgasoft.com Page 33
JAVA Means DURGASOFT
while (itr.hasNext())
{Student st =itr.next(); //type casting is not required because it is genric
System.out.println(st.sno+" "+st.sname+" "+st.smarks);
}
ListIterator<Student> ltr = ar1.listIterator(); //generic version of ListIterator
LinkedList:-
Class LinkedList extends AbstractSequentialList implements List,Deque,Queue
1) Introduced in 1.2 v
2) Heterogeneous objects are allowed.
3) Null insertion is possible.
4) Insertion ode is preserved
5) LinkedList methods are non-synchronized method
6) Duplicate objects are allowed.
7) The under laying data structure is double linkedlist.
8) cursors :- Iterator,ListIterator Ex:-LinkedList with generics.
if we are using AL to store the data at that situation whenever we are adding one new object middle of
ArrayList then number of shift operations are requires it will degrade the p
Ex:-
import java.util.*;
class Test
{
public static void main(String[] args)
{ LinkedList<String> l=new LinkedList<String>();
l.add("B");
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96
96 96 96, 9246212143 | www.durgasoft.com Page 35
JAVA Means DURGASOFT
l.add("C");
l.add("D");
l.add("E");
l.addLast("Z");//it add object in last position
l.addFirst("A");//it add object in first position
l.add(1,"A1");//add the Object spcified index
System.out.println("original content:-"+l);
l.removeFirst(); //remove first Object
l.removeLast(); //remove last t Object
System.out.println("after deletion first & last:-"+l);
l.remove("E"); //remove specified Object
l.remove(2); //remove the object of specified index
System.out.println("after deletion :-"+l);//A1 B D
String val = l.get(0); //get method used to get the element
l.set(2,val+"cahged");//set method used to replacement
System.out.println("after seting:-"+l);
}
};
D:\>java Test
original content:-[A, A1, B, C, D, E, Z]
after deletion first & last:-[A1, B, C, D, E]
after deletion :-[A1, B, D]
after seting:-[A1, B, A1cahged]
Vector :-
Case:-1
The default initial capacity of the Vector is 10 once it reaches its maximum capacity it
means when we trying to insert 11 element that capacity will become double[20].
Vector v = new Vector();
System.out.println(v.capacity()); //10
v.add("ratan");
System.out.println(v.capacity()); //10
System.out.println(v.size()); //1
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96
96 96 96, 9246212143 | www.durgasoft.com Page 36
JAVA Means DURGASOFT
Case 2:-
It is possible to create vector with specified capacity by using fallowing constructor. in
this case once vector reaches its maximum capacity then size is double based on provided initial
capacity.
Vector v = new Vector(int initial-capacity);
Vector<String> vv = new Vector<String>(3);
System.out.println(vv.capacity());//3
vv.add("aaa");
vv.add("bbb");
vv.add("ccc");
vv.add("ddd");
System.out.println(vv.capacity()); //6
System.out.println(vv.size()); //4
Case 3:-
It is possible to create vector with initial capacity and providing increment capacity by
using fallowing constructor.
Vector v = new Vector(int initial-capacity, int increment-capacity);
Vector<String> v = new Vector<String>(2,5);
System.out.println(v.capacity()); //2
v.add("ratan");
v.add("aruna");
v.add("Sravya");
System.out.println(v.capacity()); //7
System.out.println(v.size()); //3
import java.util.*;
class Test
{ public static void main(String[] args)
{ ArrayList<String> al = new ArrayList<String>();
al.add("no1");
al.add("no2");
Vector<String> v = new Vector<String>();
v.add("ratan");
v.add("aruna");
v.add("Sravya");
v.addElement("ccc");
System.out.println(v);
System.out.println(v.size());
v.add(2,"xxx");
v.remove("Sravya"); //removed based on object
v.remove(1); //removed based on index
System.out.println(v);
v.addAll(al); //adding ArrayList data into Vector
System.out.println(v);
v.removeAll(al); //it removes all objects of al
System.out.println(v);
System.out.println(v.firstElement()); //to retrieve first element
System.out.println(v.lastElement()); //to retrieve last element
}
}
D:\vikram>java Test
[ratan, aruna, Sravya, ccc]
4
[ratan, xxx, ccc]
[ratan, xxx, ccc, no1, no2]
[ratan, xxx, ccc]
ratan
ccc
Example :-
//product.java
class Product
{ //instance variables
int pid;
String pname;
double pcost;
Product(int pid,String pname,double pcost) //local variables
{ //conversion [passing local variable values to instance variable]
this.pid = pid;
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96
96 96 96, 9246212143 | www.durgasoft.com Page 38
JAVA Means DURGASOFT
this.pname = pname;
this.pcost = pcost;
}
};
//ArrayListDemo.java
import java.util.*;
class ArrayListDemo
{ public static void main(String[] args)
{ Product p1 = new Product(111,"pen",1300);
Product p2 = new Product(222,"laptop",13000);
Product p3 = new Product(333,"bag",1000);
Product p4 = new Product(444,"java",5000);
Product p5 = new Product(555,".net",4000);
Vector<Product> v = new Vector<Product>();
v.addElement(p1);
v.addElement(p2);
v.addElement(p3);
System.out.println("***Enumeration cursor only read operations***");
Enumeration<Product> e = v.elements();
while (e.hasMoreElements())
{ Product p = e.nextElement();
System.out.println(p.pid+"----"+p.pname+"----"+p.pcost);
}
System.out.println("***Iterator cursor both read & remove operations***");
Iterator<Product> itr = v.iterator();
while (itr.hasNext())
{ Product pp = itr.next();
if ((pp.pname).equals("pen"))
itr.remove(); //pen object removed
}
}
}
};
Example:-
import java.util.*;
class Test
{ public static void main(String[] args)
{
Vector<Integer> v=new Vector<Integer>();//generic version of vector
for (int i=0;i<5 ;i++ )
{ v.addElement(i); }
v.addElement(6);
v.removeElement(1); //it removes element object based
Enumeration<Integer> e = v.elements();
while (e.hasMoreElements())
{ Integer i = e.nextElement();
System.out.println(i);
}
v.clear(); //it removes all objects of vector
System.out.println(v);
}
}
Stack:- (legacy class introduced in 1.0 version)
1) It is a child class of vector
2) Introduce in 1.0 v legacy class
3) It is designed for LIFO(last in fist order )
Example:-
import java.util.*;
class Test
{ public static void main(String[] args)
{ Stack<String> s = new Stack<String>();
s.push("ratan"); //insert the data top of the stack
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96
96 96 96, 9246212143 | www.durgasoft.com Page 40
JAVA Means DURGASOFT
Example :-
import java.util.*;
class Test
{ public static void main(String[] args)
{ String reverse="";
Scanner s = new Scanner(System.in);
System.out.println("enter input string to check palendrome or not");
String str = s.nextLine();
Stack stack = new Stack();
for (int i=0;i<str.length();i++)
{ stack.push(str.charAt(i));
}
while (!stack.isEmpty())
{ reverse=reverse+stack.pop();
}
if (str.equals(reverse))
{ System.out.println("the input String palindrome");
}
else
{ System.out.println("the input String not- palindrome");
}
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96
96 96 96, 9246212143 | www.durgasoft.com Page 41
JAVA Means DURGASOFT
}
}
5) by using ListIterator we are able to read & remove & update the data.
1. It is applicable for only list type of objects.
2. By using this it is possible to read the data upate the data and delete data also.
3. By using listIterator() method we are getting LIstIterator object
EmpBean.java:-
public class EmpBean implements Comparable<EmpBean>
{ private int eid;
private String ename;
public void setEid(int eid)
{ this.eid=eid;
}
public void setEname(String ename)
{ this.ename=ename;
}
public int getEid()
{return eid;
}
public String getEname()
{return ename;
}
public int compareTo(EmpBean o)
{ if (eid==o.eid)
{return 0;
}
if (eid>o.eid)
{return 1;
}
else{return -1;}
}
};
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96
96 96 96, 9246212143 | www.durgasoft.com Page 42
JAVA Means DURGASOFT
collection(i) 1.2 v
extends
1.2v
Set(i)
implements implements
extends extends
1.4 v
LinkedHashSet(c) NavigableSet(i) 1.6v
implements
TreeSet(c 1.2v
)
HashSet:-
1) Introduced in 1.2 v.
2) Duplicate objects are not allowed if we are trying to insert duplicate values then we won't get
any compilation errors an won't get any Execution errors simply add method return old value.
3) Null insertion is possible but if we are inserting more than one null it return only one null value.
4) Heterogeneous objects are allowed.
5) The under laying data structure is HashTable.
6) It is not maintain any order the elements are return in any random order .[Insertion order is not
preserved].
7) Methods are non-synchronized.
8) cursor : Iterator
Example:-
import java.util.*;
class Test
{ public static void main(String[] args)
{ //HashSet object creation
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96
96 96 96, 9246212143 | www.durgasoft.com Page 43
JAVA Means DURGASOFT
import java.util.*;
class Test
{ public static void main(String[] args)
{ HashSet<String> h = new HashSet<String>();
h.add("ratan");
h.add("anu");
h.add("Sravya");
HashSet<String> hsub = new HashSet<String>();
hsub.add("no1");
hsub.add("no2");
hsub.addAll(h);
System.out.println(hsub.contains("anu"));
hsub.remove("anu");
System.out.println(hsub.containsAll(h));
System.out.println(hsub);
hsub.removeAll(h);
System.out.println(hsub);
hsub.retainAll(h);
System.out.println(hsub);
}
}
LinkedHashSet:-
1. Introduced in 1.4 version and It is a child class of HashSet.
2. Duplicate objects are not allowed if we are trying to insert duplicate values then we won’t get
any compilation errors an won’t get any Execution errors simply add method return false.
3. Null insertion is possible.
4. Heterogeneous objects are allowed
5. The under laying data structure is LinkedList & hashTable.
6. Insertion order is preserved.
7. Methods are non-synchronized.
8. Cursors :- Iterator.
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96
96 96 96, 9246212143 | www.durgasoft.com Page 44
JAVA Means DURGASOFT
Example:-
import java.util.*;
class Test
{ public static void main(String[] args)
{ Set<String> h = new LinkedHashSet<String>();
h.add("A");
h.add("B");
h.add("C");
h.add("D");
h.add("D");
//retrieving objects by using Iterator cursor
Iterator<String> itr = h.iterator();
while (itr.hasNext())
{String str = itr.next();
System.out.println(str);
}
//retrieving objects by using Enumeration cursor
Enumeration<String> e = Collections.enumeration(h);
while (e.hasMoreElements())
{ System.out.println(e.nextElement());
}
}
}
import java.util.*;
class Test
{ public static void main(String[] args)
{ HashSet<String> h = new HashSet<String>();
h.add("ratan");
h.add("anu");
h.add("Sravya");
//passing data from HashSet to LinkedHashSet
LinkedHashSet<String> lh = new LinkedHashSet<String>(h);
//lh.addAll(h);
lh.add("xxx");
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96
96 96 96, 9246212143 | www.durgasoft.com Page 45
JAVA Means DURGASOFT
lh.add("yyy");
System.out.println(lh);
//passing data from LinkedHashSet to HashSet
HashSet<String> hh = new HashSet<String>(lh);
//hh.addAll(lh);
hh.add("zzz");
System.out.println(hh);
}
}
TreeSet:-
1. TreeSet is same as HashSet but TreeSet sorts the elements is ascending order but HashSet does
not maintain any order.
2. The underlying data Structure is BalencedTree.
3. Insertion order is not preserved it is based some sorting order.
4. Heterogeneous data is not allowed.
5. Duplicate objects are not allowed
6. Null insertion is possible only once.
import java.util.*;
class Test
{ public static void main(String[] args)
{ TreeSet<String> t = new TreeSet<String>();
t.add("ratan");
t.add("anu");
t.add("Sravya");
System.out.println(t);
TreeSet<Integer> t1 = new TreeSet<Integer>();
t1.add(10);
t1.add(12);
t1.add(8);
System.out.println(t1);
}
}
import java.util.*;
class Test
{ public static void main(String[] args)
{ TreeSet<String> t = new TreeSet<String>();
t.add("ratan");
t.add("anu");
t.add("Sravya");
System.out.println(t);
System.out.println(t.size());
t.remove("ratan");
System.out.println(t.contains("ratan"));
t1.add("xxx");
t1.removeAll(t);
System.out.println(t1);
}
}
import java.util.*;
class Fruit
{ public static void main(String[] args)
{ TreeSet<String> t = new TreeSet<String>(new MyComp());
t.add("orange");
t.add("bananna");
t.add("apple");
System.out.println(t);
}
}
class MyComp implements Comparator<String>
{ public int compare(String s1,String s2)
{
return s1.compareTo(s2);//[apple, bananna, orange]
//return -s1.compareTo(s2);//[orange, bananna, apple]
}
};
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96
96 96 96, 9246212143 | www.durgasoft.com Page 47
JAVA Means DURGASOFT
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96
96 96 96, 9246212143 | www.durgasoft.com Page 48
JAVA Means DURGASOFT
Example :-
import java.util.Iterator;
import java.util.TreeSet;
public class Test {
public static void main(String[] args) {
// creating a TreeSet Object
TreeSet <Integer>treeadd = new TreeSet<Integer>();
// adding object in the tree set
treeadd.add(10);
treeadd.add(30);
treeadd.add(70);
treeadd.add(20);
// create iterator Object
Iterator iterator;
iterator = treeadd.iterator();
Example :-
public E first(); it print first element
public E last(); it print last element
public E lower(E); it print lower object of specified object
public E higher(E); it print higher object of specified object
public java/util/SortedSet<E> subSet(E, E); it print subset
public java/util/SortedSet<E> headSet(E); it print specified object above objects
public java/util/SortedSet<E> tailSet(E); it print specified objects below values
public E pollFirst(); it print and remove first
public E pollLast(); it print and remove last.
import java.util.*;
class Test
{ public static void main(String[] args)
{ //creating TreeSet object
TreeSet t=new TreeSet();
//adding object in TreeSet
t.add(50); t.add(20); t.add(40);
t.add(10); t.add(30);
System.out.println(t);
SortedSet s1=t.headSet(50);
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96
96 96 96, 9246212143 | www.durgasoft.com Page 49
JAVA Means DURGASOFT
System.out.println(s1); //[10,20,30,40]
SortedSet s2=t.tailSet(30);
System.out.println(s2); //[30,40,50]
SortedSet s3=t.subSet(20,50);
System.out.println(s3); //[20,30,40]
System.out.println("last element="+t.last());
System.out.println("first element="+t.first());
System.out.println("lower element="+t.lower(50));
System.out.println("higher element="+t.higher(20));
System.out.println("print & remove first element="+t.pollFirst());
System.out.println("print & remove last element="+t.pollLast());
System.out.println("final elements="+t);
System.out.println("TreeSet size="+t.size());
System.out.println("TreeSet size="+t.remove(10));
System.out.println("TreeSet size="+t.remove(30));
}
}
D:\morn11>java Test
[10, 20, 30, 40, 50]
[10, 20, 30, 40]
[30, 40, 50]
[20, 30, 40]
last element=50
first element=10
lower element=40
igher element=30
print & remove first element=10
print & remove last element=50
final elements=[20, 30, 40]
TreeSet size=3
TreeSet size=false
TreeSet size=true
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96
96 96 96, 9246212143 | www.durgasoft.com Page 50
JAVA Means DURGASOFT
Map interface:-
1.2v
Map(i)
implements implements
extends extends
1.4 v
LinkedHashMap(c NavigableMap(i) 1.6v
)
implements
TreeMap(C) 1.2v
Map:-
1. Map is a child interface of collection.
2. Up to know we are working with single object and single value where as in the map collections
we are working with two objects and two elements.
3. The main purpose of the collection is to compare the key value pairs and to perform necessary
operation.
4. The key and value pairs we can call it as map Entry.
5. Both keys and values are objects only.
6. In entire collection keys can’t be duplicated but values can be duplicate.
HashMap:-
1) interdicted in 1.2 version
2) Heterogeneous data allowed.
3) Underlying data Structure is HashTable.
4) Duplicate keys are not allowed but values can be duplicated.
5) Insertion order is not preserved.
6) Null is allowed for key(only once)and allows for values any number of times.
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96
96 96 96, 9246212143 | www.durgasoft.com Page 51
JAVA Means DURGASOFT
7) Every method is non-synchronized so multiple Threads are operate at a time hence permanence
is high.
8) cursor :- Iterator.
Example :-
import java.util.*;
class Test
{ public static void main(String[] args)
{ //creation of HashMap Object
HashMap h = newHashMap();
h.put("ratan",111); //h.put(key,value);
h.put("anu",111);
h.put("banu",111);
Set s1=h.keySet(); //used to get all keys
System.out.println("all keys:--->"+s1);
Collection c = h.values(); //used to get all values
System.out.println("all values--->"+c);
Set ss = h.enrySet(); //it returns all entryes nathing but [key,value]
System.out.println("all entries--->"+ss);
//get the Iterator Object
Iterator itr = ss.iterator();
while (itr.hasNext())
{
//next() method retrun first entry to represent that entery do typeCasting
Map.Entry m= (Map.Entry)itr.next();
System.out.println(m.getKey()+"----"+m.getValue()); //printing key and value
}
}
};
LinkedHashMap:-
1) interdicted in 1.4 version
2) Heterogeneous data allowed.
3) Underlying data Structure is HashTable & linkedlist.
4) Duplicate keys are not allowed but values can be duplicated.
5) Insertion order is preserved.
6) Null is allowed for key(only once)and allows for values any number of times.
7) Every method is non-synchronized so multiple Threads are operate at a time hence permanence
is high.
8) cursor :- Iterator
Test.java:-
import java.util.*;
class Test
{ public static void main(String[] args)
{
//creates LinkedList object with generic version
LinkedHashMap<Emp,Student> h = new LinkedHashMap<Emp,Student>();
h.put(new Emp(111,"ratan"), new Student(1,"budha"));
h.put(new Emp(222,"anu"), new Student(2,"ashok"));
//get Set interface before getting Iterator object
Set s = h.entrySet();
//creates iterator Object
Iterator itr = s.iterator();
while (itr.hasNext())
{//holding Entry by using Entry interface
Map.Entry m = (Map.Entry)itr.next();
Emp e = (Emp)m.getKey(); //getting Emp object
System.out.println(e.ename+"--"+e.eid);
Student ss = (Student)m.getValue();//getting Student object
System.out.println(ss.sname+"--"+ss.sid);
}
}
}
import java.util.*;
class Test
{ public static void main(String[] args)
{ HashMap h = new LinkedHashMap();
h.put(111,"ratan");
h.put(222,"anu");
h.put(333,"sravya");
System.out.println(h);
Set s1 = h.keySet();
System.out.println(s1);
Collection c = h.values();
System.out.println(c);
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96
96 96 96, 9246212143 | www.durgasoft.com Page 53
JAVA Means DURGASOFT
Set s2 = h.entrySet();
Iterator itr = s2.iterator();
while (itr.hasNext())
{ Map.Entry m = (Map.Entry)itr.next();
System.out.println(m.getKey()+"---"+m.getValue());
}
}
}
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96
96 96 96, 9246212143 | www.durgasoft.com Page 54
JAVA Means DURGASOFT
HashTable:-
1. Introduced in the 1.0 version it’s a legacy class.
2. Every method is synchronized hence only one thread is allowed to access it is a Thread safe but
performance is decreased.
3. Null insertion is not possible if we are trying to insert null values we are getting
NullPointerException.
h.put(null,"ratan");
h.put("4",null);
Ex:-
import java.util.Hashtable;
import java.util.Collection;
import java.util.Set;
class Test
{ public static void main(String[] args)
{ Hashtable<String,String> h = new Hashtable<String,String>();
//adding data in HashTable
h.put("1","one");
h.put("2","two");
h.put("3","three");
System.out.println(h);
System.out.println(h.get("1"));//one
System.out.println(h.isEmpty());
h.remove("3");
System.out.println(h.containsKey("1"));
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96
96 96 96, 9246212143 | www.durgasoft.com Page 55
JAVA Means DURGASOFT
System.out.println(h.containsKey("3"));
System.out.println(h.containsValue("one"));
System.out.println(h.size());
//to get all values objects
Collection<String> c = h.values();
for (String i : c)
{ System.out.println(i);
}
//to get all key objects
Set<String> s = h.keySet();
for (String ss : s)
{ System.out.println(ss);
}
}
}
Example :-
We are able to add one class data into another class in two ways
1) Passing one class reference variable to another class
Hashtable h = new Hashtable();
HashMap<String,String> h1 = new HashMap<String,String>(h);
2) By using putAll() method
h1.putAll(h);
import java.util.Hashtable;
import java.util.*;
class Test
{ public static void main(String[] args)
{ Hashtable<String,String> h = new Hashtable<String,String>();
h.put("1","one");
h.put("2","two");
h.put("3","three");
//passing Hashtable data into HashMap
HashMap<String,String> h1 = new HashMap<String,String>(h);
//h1.putAll(h);
h1.put("hm","ratan");
System.out.println(h1);
//passing HashMap data into LinkedHashMap
LinkedHashMap<String,String> lhm = new LinkedHashMap<String,String>(h1);
//lhm.putAll(h1);
lhm.put("lhm","anu");
System.out.println(lhm);
}
}
TreeMap:-
Example-1:-
import java.util.TreeMap;
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96
96 96 96, 9246212143 | www.durgasoft.com Page 56
JAVA Means DURGASOFT
class Test
{ public static void main(String[] args)
{ TreeMap<String,String> tmain = new TreeMap<String,String>();
tmain.put("ratan","no1");
tmain.put("anu","no2");
if (tmain.containsKey("ratan"))
{System.out.println("ratan is great");
}
if (tsub.containsValue("no1"))
{System.out.println("no1 ratan only");
}
//printing all the keys
Set<String> s = tsub.keySet();
for (String ss : s)
{ System.out.println(ss);
}
//printing all the values
Collection<String> s1 = tsub.values();
for (String ss1 : s1)
{ System.out.println(ss1);
}
Set<Entry<String,String>> s2 = tsub.entrySet();
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96
96 96 96, 9246212143 | www.durgasoft.com Page 57
JAVA Means DURGASOFT
Java.util.Properties:-
Abc.properties :-
username = system
password = manager
driver = oracle.jdbc.driver.OracleDriver
trainer = Ratan
Test.java:-
import java.util.*;
import java.io.*;
class Test
{ public static void main(String[] args) throws FileNotFoundException,IOException
{
//locate properties file
FileInputStream fis=new FileInputStream("abc.properties");
//load the properties file by using load() method of Properties class
Properties p = new Properties();
p.load(fis);
//get the data from properties class by using getProperty()
String username = p.getProperty("username");
String driver = p.getProperty("driver");
String password = p.getProperty("password");
String trainer = p.getProperty("trainer");
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96
96 96 96, 9246212143 | www.durgasoft.com Page 58
JAVA Means DURGASOFT
If first object sid value is greater than existing object then it returns positive//no change in data
If the object sid values is less than existing object then it returns negative.//change location
If any negative or both are equals then it returns zero. //no change in data
Student.java
class Student implements Comparable
{ int sid;
String sname;
Student(int sid,String sname)//local var
{ this.sname=sname; this.sid=sid;
}
public int compareTo(Object obj)
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96
96 96 96, 9246212143 | www.durgasoft.com Page 59
JAVA Means DURGASOFT
{ Student s = (Student)obj;
if (sid>s.sid)
{return 1;
}
if (sid<s.sid)
{return -1;
}
If(sid==0){
return 0;}
}
}
Test.java:-
import java.util.*;
class Test
{
public static void main(String[] args)
{
ArrayList<Student> al = new ArrayList<Student>();
al.add(new Student(11,"ratan"));
al.add(new Student(2,"Sravya"));
al.add(new Student(333,"anu"));
Collections.sort(al);
Iterator<Student> itr =al.iterator();
while (itr.hasNext())
{ Student s = itr.next();
System.out.println(s.sid+"----"+s.sname);
}
}
}
import java.util.*;
class Comp implements Comparator
{
public int compare(Object o1,Object o2)
{
EmpBean e1 = (EmpBean)o1;
EmpBean e2 = (EmpBean)o2;
if (e1.eid==e2.eid)
{return 0;
}
if (e1.eid>e1.eid)
{return 1;
}
else{return -1;}
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96
96 96 96, 9246212143 | www.durgasoft.com Page 60
JAVA Means DURGASOFT
}
}
import java.util.*;
class Test
{ public static void main(String[] args)
{
TreeSet<EmpBean> s = new TreeSet<EmpBean>(new Comp());
EmpBean e1 = new EmpBean();
e1.setEid(111);
e1.setEname("ratan");
EmpBean e2 = new EmpBean();
e2.setEid(22);
e2.setEname("anu");
s.add(e1);
s.add(e2);
}
}
public class EmpBean implements Comparable<EmpBean>
{ int eid;
String ename;
public void setEid(int eid)
{ this.eid=eid;
}
public void setEname(String ename)
{ this.ename=ename;
}
public int getEid()
{return eid;
}
public String getEname()
{return ename;
}
public int compareTo(EmpBean o)
{
if (eid==o.eid)
{return 0;
}
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96
96 96 96, 9246212143 | www.durgasoft.com Page 61
JAVA Means DURGASOFT
if (eid>o.eid)
{return 1;
}
else{return -1;}
}
};
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96
96 96 96, 9246212143 | www.durgasoft.com Page 62
JAVA Means DURGASOFT
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96
96 96 96, 9246212143 | www.durgasoft.com Page 63