Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 79

K.V.R Sir 11am JSE Collection Frame Work (java.util.

*): Collection Framework is one of the additional service or add on service developed by SUN Micro systems and supplied as a part of java software for enhancing the performance of java applications. Def: Collection framework is the standardized mechanism of java which allows grouping different types of values or similar types of values or both in a single variable with dynamic size. This single variable is known as Collection Framework. In order to deal with Collection Framework programming we must import a predefined package called java.util.* Q) What are the differences between Arrays and Collection frame work? Arrays 1. An array is a collective name given to group of memory locations which are all referred by similar type of values. Collection Framework 1. Collection framework is one of the standard mechanisms of java which allows us to group similar type of values or both in a single variable with dynamic size in nature. This single variable is known as Collection frame work variable. 2. CollctionFreamework concept allows both homogeneous and heterogeneous values. 3. Collection collectionFrameWork contains dynamic size in nature.

2. Concept of arrays allows only homogenious values but not hetrogenious values. 3. Concept of arrays contains fixed size in nature.

Aims/Goals/Characteristics/ Properties of Collection Framework: 1. Considerable Performance is achieved. 2. Inbuilt adaptability is achieved (The mechanism of adding the content of one collection framework variable to another collection framework variable either in the beginning or in the last or in the middle is known as adaptability). 3. Collection Framework variables are always extendable( The mechanism of increasing the size of the collection Framework variable depends on the incoming flow of the data is known as Extendable) 4. Collection Framework is one of the algorithmic oriented. 4.1 Collection Framework provides inbuilt sorting techniques. 4.2 Collection Framework provides inbuilt searching techniques. 4.3 Collection Framework provides preliminary concepts of data structures such as stacks, Linked lists, queues and Trees e.t.c.,
1

K.V.R Sir 11am JSE Types of Collection Frameworks: In the earliar versions of java the concept of Collection framework is known as Data Structures. The concept of data structures are not full filling the some of demands in the industry. So SUN Micros system developed the concept of Collection Framework. In other words revised form of the data structures are also known as Collection Framework. So revised form Data structures is known as new Collection Framework, renamed form of Collection Framework is known as Legacy Collection Framework. 1. New Collection Framework: New Collection Framework divided into two forms those are i) 1D Single Collection Framework ii) 2D Collection Framework/maps. 1D Collection Framework: A 1D Collection Framework variable is one which data is organizing in the form of rows and columns not in the form of (key, value). 2D Collection Framework: A 2D Collection Framework variable is one which data organized in the form of (key, value). In (key, Value) the key must be unique or distinct, value may be distinct or not. 1D Collection Framework Example: In Order to deal with 1D collection Framework programming we must know about interfaces and classes of 1D Collection Framework and they are present in java.util.* package. 1D Collection Framework interfaces: 1D collection Framework interfaces are classified into four types they are 1. 2. 3. 4. Java.util.Collection Java.util.List Java.util.Set Java.util.SortedSet

Collection 2

K.V.R Sir 11am JSE

List

Set

SortedSet

Differences between Collection, Lsit, Set, SortedSet: Collection 1. Collection is an interface which is available on the top of hierarchy of all the collection Framework interfaces 2. An Object of Collection Framework interface allows to us to add duplicate elements 3. Collection interface Object allows us add data only at end this is called static insertion. 4. An Object of Collection interface List 1. List is the sub interface of Collection. Set 1. Set is the sub interface of Collection. SortedSet 1. SortedSet is the sub interface of Set.

2. An Object of List interface allows us to add duplicate elements.

2. An Object of List interface allows us to add unique/ distinct elements. 3. Collection interface Object allows us add data only at end this is called static insertion. 4. An Object of Set interface always
3

2. An Object of List interface allows us to add unique/ distinct elements. 3. Collection interface Object allows us add data only at end this is called static insertion. 4. An Object of SortedSet

3. An Object of List interface allows us to add data dynamically either in the beginning or middle or last. 4. An Object of List interface always

K.V.R Sir 11am JSE always displays the data in random order. displays the data in sequential order. 5. An object of List allows us to retrieve the data either in forward direction or backward direction . displays the data in random order. interface always displays the data in sorted order

5. An Object of collection always access to retrieve the data only in forward direction. Note:

5. An Object of collection always access to retrieve the data only in forward direction.

5. An Object of collection always access to retrieve the data only in forward direction.

1. The objects of Set, Collection, Sorted set interfaces are known as unidirectional objects because they allows to retrieve the data only in forward direction. 2. The objects of List interface is known as multidirectional objects because they allow to retrieve the data only in forward direction. 1D Collection Framework process: The steps 1,2, 3 are used for performing assembling phase and steps 4,5,6 are used to performing de assembling phase.

All the entries of 1Dimensional Collection Framework are treated as Objects of java.lang.Object.
4

K.V.R Sir 11am JSE

Add wrapper class objects in Collection Framework Variable

Retrieve all the entries of 1Dimenstional Collection Framework variable and hold them in Object of java.lang.Object.
4

Convert Fundamental values into wrapper class Objects.


2

Convert object of java.lang.Object into wrapper class object.


5

Fundamental Values.
1

Convert wrapper class object into fundamental values.


6

Methods in java.util.Collection: we know that collection is one of the top most interface in the hierarchy of all the 1D Collection Framework interfaces. 1. Public int Size(): This method is used for determining the number of elements present in Collection Frame work variable. 2. Public boolean isEmpty(): This method returns true provided Collection Frame work variables containing any elements(0 elements empty) otherwise it returns false( non empty). 3. Public boolean add(Object): i. This method is used for adding data to any collection Framework variable only at the end. As long as we call this method with respective collection and list of interface objects it returns true.

K.V.R Sir 11am JSE ii. There is case of returning false because these allow duplicates. When we call this method with respect to set and sortedSet interface object and if we try to add duplicates then we get this method returns false because Object never allows duplicates. 4. Public boolean addAll (Collection): This method is used for adding content of one Collection Framework variable to another Collection Framework variable which is nothing but adoptability. 5. Public Iterator iterator: This method is used for extracting or retrieving all the elements of any Collection Framework Variable and forms like a chine. This method returns an Object of Iterator interface and it is by default pointing just before the first element of any Collection Framework variable. EX: System.out.println(c); // [10,20,30,40] Integer itr=c.iterator(); itr
10 20 30 40

int s=0 while(itr.hasNext()) { Object obj.itr.Next(); //4 step Integer io=(Integer) obj // 5 step int x= io.intValue(); //6 step System.out.println(x); } System.out.println(sum=+s); 6. Public Object[] toArray(); This method is used for converting all the elements of Collection Framework variable in the form of Array of Objects of java.lang.Object.

K.V.R Sir 11am JSE

Obj
10

C
10 20

20

30 40

30 40

System.out.println(c); //10 20 30 40 Object obj[] = c.toArray()

int s=0 for(int i=0;i<obj.length;i++) { Integer io=(Interger) obj[5] int x=io.intValue(); System.out.println(x); // 10 20 30 40 S=s+x; } System.out.println(sum=+s); Iterator interface: Iterator interface is one of the predefined interface present in java.util.* package. The purpose of iterater interface Object is to extract the data of any Collection
7

K.V.R Sir 11am JSE Framework variable in forward direction for individual processing of the elements. Whenever we create an object of iterator interface by default it is pointing just before the first element of Collection Framework Variable. Methods a) Public boolean hasNext b) Public Object Next() Method a is always used for checking whether we have next element or not in the Collection Framework variable. If we have next element then it returns true otherwise it returns false. Method b is used for obtaining next element of any Collection Framework variable with respective an object of iterator interface provided method returns true. Methods is java.util.List: List is the interface collection so that all the methods of collection are inherited into list. 1. Public void add(int, Object): This method is used for adding an element to any Collection Framework variable either in the beginning or in the middle or in the last that is dynamic iterations can be possible. Q) How do you add an element 60 at the end of List interface Object by making use of add(int, Object)?
10

0 1
Sathya 40 A ----------60

3 4

A) l.add(l.Size(), new Integer(60)); EX: l.add(4, new Integer(60)); When the above statement is executed internally JVM considers the following statement. l.add(4, new Integer(60));
8

K.V.R Sir 11am JSE

2. Public Object get(int): This method is used for obtaining the value from the Collection Framework variable by passing from the specific position. EX: Object obj=l.get(2) 30 System.out.println(obj); Object obj=l.get(2) Null System.out.println(obj1); Note: If right hand side method is successfully executed then an Object of L.H.S variable contains not null value in the case of Object as a return type and contains default value in the case of fundamental return type. 3. Public Object remove(int) 4. Public void remove(Object) The above methods are removing the values from a Collection Framework variable either based on position based on content especially while we are removing the values from Collection Framework variable based on the content, only first occurrence is removed by matching with case and meaning. 5. Public void removeAll(): This method is used for removing all elements of Collection Framework variable. 6. Public void ListIterator listListIterator(): This method is used for retrieving all the elements of Collection Framework variable and forms like a chine and just before the first element of List Collection Framework variable. Litr
10 20 30 40

System.out.println(l); //[10 20 30 40] ListIterator litr=new ListIterator();

While(litr.hasNext())
9

K.V.R Sir 11am JSE { Object obj=litr.Next() System.out.println(obj); // 10 20 30 40 } Int s=0;


10 20 30 40

After Last While(litr.hasPrevious()) { Object obj1=litr.Previous(); //4 Iterator io=(Integer)obj; //5 Int x=io.intValue() // 6 System.out.println(x);// 40 30 20 10 List Iterator: 1. List Iterator is one of the predefined interface present in java.util.* package. The functionality of List Iterator interface Object is to retrieve the data from any Collection Framework variable either in forward or backward direction or in both directions. 2. Whenever we create an Object of iterator interface, it is by default pointing just before the first element of any Collection Framework variable like iterator interface Object. Iterator interface is the super interface for List iterator. Methods: 1. 2. 3. 4. Public boolean hasNext() Public Object Next() Public boolean hasPrevious Public Object Previous Method 3 is always used for verifying whether we have previous element or not in the collection Framework variable.

10

K.V.R Sir 11am JSE This method returns true provide Collection Framework variable is having previous element otherwise it returns false. Method 4 is used for obtaining previous element of any Collection Framework variable with respective ListIterator interface Object provided method 3 returns true. Q) What are the differences between Iterator and ListIterator interface? Iterator 1. Iterator is one of the super interface 2. An object of iterator is always used for retrieving values of any Collection Framework variable only in forward direction. 3. i) Public boolean hasNext() ii) public Object Next() ListIterator 1. ListIterator is one of the sub interface of Iterator. 2. An object of Listiterator is always used for retrieving values of any Collection Framework variable in both forward and backward direction. 3. i) Public boolean hasPrevious() ii) public Object Previous()

Q) What are the methods are used for retrieving the data from any Collection Framework Variable? 1. Public Object[] to Array() 2. public Iterator iterator() 3. Public ListIterator Listiterator() Methods in Set: 1. The interface set is one of the sub interface of set so that all the methods of Collection are inherited into Set. 2. The interface Set does not contain any special methods on its own except Collection methods. 3. Even though Collection and set interface methods are same, the methods of Collection defined in some predefined classes in such a way that duplicate elements are allowed and displaying in the random order. 4. Whereas methods of set are defined in some other predefined class in such a way that unique elements are allowed and displayed in random order. 5. In other words even though methods of Set and Collection are same their implementations (definitions) are different in different predefined classes. 4. Methods in java.util.SortedSet:
11

K.V.R Sir 11am JSE

1. Sorted set is one of the sub interface of Set so that all the methods of Set are inherited into SortedSet (Which are nothing but Collection method) 2. Even though methods of Set and SortedSet are same, methods of set are defined in some predefined classes in such a way that unique elements are allowed and displayed in random order. 3. Whereas SortedSet Methods are defined in some other predefined class in such a way that unique elements are allowed and displayed Sorted order. In other words even though the methods of Set and SortedSet are same their implementations are different predefined classes. In recent versions found the following methods which are used for splitting the elements of SortedSet. 1. Public Object first() Xi<=Obj1 2. Public Object last() 3. Public SortedSet headSet(Object obj) 4. Public SortedSet subSet(Object obj1, Object1 obj2) Obj1<=xi>obj2

5. Public SotedSet tailSet(Object1 obj) Here xi represents values of SortedSet.

Xi>Obj

EX: SortedSet Object fobj=ss.fobj()


10 30 40 12 10 20

SortedSet hs=ss.headSet(newInteger(30))
10 20 30

K.V.R Sir 11am JSE

SortedSet ms=ss.Subset(new Integer(40), new Integer(70))


40 50

60

SortedSet ts=ss.tailSet(new Integer(60))


70

Object lobj=ss.lobj()
80

80

1.

In other words 1,2,3,4 are acting as a middleware layer between predefined 1D Collection Framework interfaces and predefined 1d Collection Concrete Classes. 2. The Classes 5,6,7,8 are predefined 1D Collection Framework concrete classes which are suitable for dealing with the current industry requirements. 3. So in the real world we use directly the classes 5,6,7,8. 1D Collection Framework Classes: 1. 2. 3. 4. Collection List Set SortedSet 1. AbstractCollection impl 2. AbstractList extends/impl 3. AbstractSet extends/impl 4.AbstractSequentialList 5.LinkedList 6.ArrayList 7.HashSet 8.TreeSet extends Collection AbstractCollectionList AbstractCollectionSet AbstractList

extends extends extends


13

AbstractSequentialList AbstractSet

AbstractSet

K.V.R Sir 11am JSE Implements SortedSet

java.util.LinkedList: It is one of the bottom most 1D Collection Framework bottom most concrete class. Creating LinkedList is nothing but creating an Object of LinkedList Class. LinkedList ll=new LinkedList(); ll
Data Address

Here ll is one of the Collection Framework variable and it represents the name of the node. 1. In the LinkedList the data is organized in the form of nodes. Node contains two parts whose structure is given below. Node
Data 1 address 2

2. Here node repr presents Object name of LinkedLsit class. Data part represents the type of data being s. stored in the LinkedList. Address part represents address of the next nodeand address part of the last node contains null. Which illustrates end of the LinkedList. 3. EX: Represent the values 10,20,30,40,50 ll
10

1 (i-1) th
20 1020

2 ith
30 1030

3 (i+1)th
40 1040

4(i+2)
50 1050

1010

1000

1010

1020

1030

1040

4. * The data is organized in LinkedList in such a way that address of ith node stored in part of i-1th node and address of the ith node contains address of i-1 th node and for the last node address part must be null which indicates end of the LinkedList.

14

K.V.R Sir 11am JSE Advantages of LinkedList: i. ii. iii. LinkedList allows us to add both homogeneous and heterogeneous values. LinkedList always gives always dynamic size in natrure. LinkedList allows us to add the data either in beginning or in the last or middle.

Hierarchy:
LinkedLi st AbstractSequntialL ist AbstractList AbstractC ollection Collection

List

Profile: Constructors: 1. LinkedList() 2. LinkedList(int size) Instance Methods 3. 4. 5. 6. 7. 8. Public Object getFirst() Public Object getLast() Public Object removeFirst() Public Object removeLast() Public void addFirst(Object) Public void addLast(Object)

P) Write a java program which illustrates the concept of LinkedList?


15

K.V.R Sir 11am JSE import java.util.*; class LL { public static void main(String args[]) { LinkedList ll=new LinkedList(); System.out.println("Content="+ll); //[] System.out.println("Is empty?="+ll.isEmpty()); //add the elements to ll ll.add(new Integer(10)); ll.add(new Integer(20)); ll.add(new Integer(30)); ll.add(new Integer(40)); System.out.println("Content="+ll); System.out.println("Size="+ll.size()); System.out.println("isEmpty?="+ll.isEmpty()); //add elements at first and last position ll.addFirst(new Integer(10)); ll.addFirst(new Integer(50)); System.out.println("Content="+ll); //[10 20 30 40 50] //extract elements from ll System.out.println("extract elements from ll using iteratir()"); Iterator itr=ll.iterator(); int s=0;

16

K.V.R Sir 11am JSE while(itr.hasNext()) { Object obj=itr.next(); Integer io=(Integer)obj; // Object Type Casting int x=io.intValue(); System.out.println(x); s=s+x; } System.out.println("sum using Iterator="+s); System.out.println("extract the elements form ll using listIterator"); ListIterator litr=ll.listIterator(); while(litr.hasNext()) { Object obj1=litr.next(); System.out.println(obj1); //10 20 30 40 } System.out.println("extract the elements from ll using List Iterator"); int s1=0; while(litr.hasPrevious()) { Object obj2=litr.previous(); Integer io1=(Integer)obj2; int x1=io1.intValue(); System.out.println(x1);

17

K.V.R Sir 11am JSE s1=s1+x1; } System.out.println("Sum using ListIterator="+s1); System.out.println("extract the elements from ll using toArray()"); Object obj3[]=ll.toArray(); for(int i=0;i<obj3.length;i++) { System.out.println(obj3[i]); } System.out.println("extract elements from ll-random position"); Object robj=ll.get(2); System.out.println("random element ="+robj); //30 } } /*OUTPUT

C:\>javac LL.java Note: LL.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details.

C:\>java LL Content=[] Is empty?=true Content=[10, 20, 30, 40]

18

K.V.R Sir 11am JSE Size=4 isEmpty?=false Content=[50, 10, 10, 20, 30, 40] extract elements from ll using iteratir() 50 10 10 20 30 40 sum using Iterator=160 extract the elements form ll using listIterator 50 10 10 20 30 40 extract the elements from ll using List Iterator 40 30 20 10 10

19

K.V.R Sir 11am JSE 50 Sum using ListIterator=160 extract the elements from ll using toArray() 50 10 10 20 30 40 extract elements from ll-random position random element =10 */ Note: While we are writing Collection Framework based applications it is highly recommended to follow Uses_A relationship. P) Write a program for LinkedList to deal with all operations import java.util.*; class practicedemo { public static void main(String args[]) { LinkedList ll=new LinkedList(); LinkedList ll1=new LinkedList(); LinkedList ll2=new LinkedList(); System.out.println("Finding the size of the Linked list"); System.out.println(ll.size());
20

K.V.R Sir 11am JSE System.out.println("Just Displaying the LikedList"+ll); System.out.println("Finding the whether Linked List is Empty or not"); System.out.println(ll.isEmpty()); System.out.println("To add the values into Linked List"); ll.add(10); ll.add(20); ll.add(12.5); ll.add("Bhargav"); ll.add('c'); ll.add(12.5f); ll.add(true); System.out.println("llAdded values"+ll); ll1.add(10); ll1.add(20); ll1.add(30); ll1.add(40); ll1.add(50); System.out.println("ll1 added values"+ll1); System.out.println("to add all collections once"); ll2.addAll(ll); System.out.println(ll2); Object obj5=ll.remove(2); System.out.println("removed items in hte positions="+obj5); Iterator itr=ll1.iterator();

21

K.V.R Sir 11am JSE Object obj6=ll.add(3); System.out.println("Add items are ="+obj6); //List First method. int s=0; while(itr.hasNext()) { Object obj1=itr.next(); System.out.println(obj1); Integer io=(Integer)obj1; int x=io.intValue(); s=s+x; } System.out.println(s); Object obj2[]=ll.toArray(); for(int i=0;i<obj2.length;i++) { System.out.println(obj2[i]); } Object obj4=ll.get(2); System.out.println("the second value"+obj4);

} } Limitations of a LinkedList?

22

K.V.R Sir 11am JSE 1. More space: We know that LinkedList is a collection of Nodes which memory space of data part and address part (Constant value) are explicitly stored in heap memory anything is stored in heap memory takes more space). 2. More Execution time: After retrieving first node value to retrieve the second node value, JVM retrieves the address of second node from address part of first node. It is one of the time consuming process. Conclusion: The above two factors on performance of LinkedList application development to avoid the above limitations we make use of ArrayList. Java.util.ArrayList: 1. ArrayList is one of the bottom most 1D Collection Framework concrete sub class of all abstract classes of 1D Collection Framework. 2. Creating ArrayList is nothing but creating an Object of ArrayList class. EX: ArrayList al=new ArrayList();
10 20 30 40

Here al is one of the Collection Framework variable. Internally all the elements of ArrayList organizes in the form of cells. All the elements of ArrayList processes based on the concept of Zero based Indexing. That is all the elements of ArrayList qualified with the positions start from 0,1,------,n-1. Internally all the cell values of ArrayList stored in heap memory and cell addresses are stored in associative memory anything we store in associative memory. Anything we store in Associative memory, it takes negligible amount of space ad anything we retrieve from associative memory it takes negligible time.

Hierarchy: ArrayList ListAbstractSequentialListAbstractList

AbstractCollection Collection List


23

K.V.R Sir 11am JSE Profile: Constructor: 1. ArrayList(): This constructor is used for creating an Object of ArrayList. EX: ArrayList al=new ArrayList();

al

Depending on incoming flow of the data the size of ArrayList can be expanded. Advantages of ArrayList over LinkedList: In the place of the LinkedList we use ArrayList for Collection Framework variable based applications, we get the following advantages. 1. Less memory space since cell addresses are stored in associative memory. 2. Less Execution time since retrieving the cell address from associative memory is neglisible. Here above 1 and 2 points makes us to understand ArrayList provides more performance than LinkedList. Hence industry is always recommended to make use of ArrayList compared to LinkedLsit. P) Write a java program which illustrates the concept of ArrayList. import java.util.*; class AL { public static void main(String args[]) { ArrayList ll=new ArrayList(); System.out.println("Content="+ll); //[] System.out.println("Is empty?="+ll.isEmpty()); //add the elements to ll
24

K.V.R Sir 11am JSE ll.add(new Integer(10)); ll.add(new Integer(20)); ll.add(new Integer(30)); ll.add(new Integer(40)); System.out.println("Content="+ll); System.out.println("Size="+ll.size()); System.out.println("isEmpty?="+ll.isEmpty()); //add elements at first and last position ll.add(0,new Integer(10)); ll.add(ll.size(),new Integer(50)); System.out.println("Content="+ll); //[10 20 30 40 50] //extract elements from ll System.out.println("extract elements from ll using iteratir()"); Iterator itr=ll.iterator(); int s=0; while(itr.hasNext()) { Object obj=itr.next(); Integer io=(Integer)obj; // Object Type Casting int x=io.intValue(); System.out.println(x); s=s+x; } System.out.println("sum using Iterator="+s);

25

K.V.R Sir 11am JSE System.out.println("extract the elements form ll using listIterator"); ListIterator litr=ll.listIterator(); while(litr.hasNext()) { Object obj1=litr.next(); System.out.println(obj1); //10 20 30 40

} System.out.println("extract the elements from ll using List Iterator"); int s1=0; while(litr.hasPrevious()) { Object obj2=litr.previous(); Integer io1=(Integer)obj2; int x1=io1.intValue(); System.out.println(x1); s1=s1+x1; } System.out.println("Sum using ListIterator="+s1); System.out.println("extract the elements from ll using toArray()"); Object obj3[]=ll.toArray(); for(int i=0;i<obj3.length;i++) { System.out.println(obj3[i]);

26

K.V.R Sir 11am JSE } System.out.println("extract elements from ll-random position"); Object robj=ll.get(2); System.out.println("random element ="+robj); //30 } } /*OUTPUT

C:\>javac AL.java Note: AL.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details.

C:\>java AL Content=[] Is empty?=true Content=[10, 20, 30, 40] Size=4 isEmpty?=false Content=[10, 10, 20, 30, 40, 50] extract elements from ll using iteratir() 10 10 20 30

27

K.V.R Sir 11am JSE 40 50 sum using Iterator=160 extract the elements form ll using listIterator 10 10 20 30 40 50 extract the elements from ll using List Iterator 50 40 30 20 10 10 Sum using ListIterator=160 extract the elements from ll using toArray() 10 10 20 30 40

28

K.V.R Sir 11am JSE 50 extract elements from ll-random position random element =20 */ P) Write a Java program to sort Arraylist Elements. import java.util.*; class TypeWrap { public static void main(String args[]) { ArrayList ll=new ArrayList(); // LinkedList ll=new LinkedList(); System.out.println("Content="+ll); //[] System.out.println("Is empty?="+ll.isEmpty()); //add the elements to ll Scanner s=new Scanner(System.in); System.out.println("enter first number"); ll.add(s.nextInt()); System.out.println("enter second number"); ll.add(s.nextInt()); System.out.println("enter third number"); ll.add(s.nextInt()); System.out.println("enter fourth number"); ll.add(s.nextInt());

29

K.V.R Sir 11am JSE Collections.sort(ll); System.out.println(ll); } } /* OUTPUT

C:\>java TypeWrap Content=[] Is empty?=true enter first number 3 enter second number 23 enter third number -12 enter fourth number -12 [-12, -12, 3, 23] */

HashSet and TreeSet: HashSet and TreeSet are the bottom most derived classes of 1D Collection Framework abstract classes.

1. HashSet 1. An Object of HashSet allows only unique elements.


30

2. TreeSet 1. An Object of TreeSet also allows unique elements.

K.V.R Sir 11am JSE 2. An Object of HashSet organizes data in the form of Hash Table by following hasing mechanism. 3. Whatever the data we are adding to the HashSet class object we are unable to determine in what order HashSet class order displays the data because we are not knowing which hasing mechanism is followed by SUN Micro system and they did not disclose that is Undetermined form. 4. The operations like insertion and deletion and modification takes considerable amount of time those are more expensive operations. 5. Retrieving the data from HashSet takes more amount of time(due to HashCode calculation) 6. Creating HashSet is nothing but creating an Object of HashSet Class. EX: HashSet hs=new HashSet() 7. HashSet() 8. Collection AbstractCollection AbstractSet AbstractSet HashSet TreeSet SortedSet Set AbstractCollection Set 2. An Object of TreeSet organizes the data in the form of Nodes by following the Binary Tree. 3. TreeSet class Object always displays the data in Stored form

4. The operation like insertion and deletion and modification takes neglisible amount of time that is less expensive operations. 5. Retrieving the data from TreeSet takes more less of time (Due to hash code calculation). 6. Creating TreeSet is nothing but creatin TreeSet Object of TreeSet Call. EX: TreeSet ts=new TreeSet() 7. TreeSet() 8. Collection

Conclusion: Industry is highly recommended to use TreeSet instead of HashSet. P) Write a java program which illustrates the concept of HashSet and TreeSet. import java.util.*; class hset

31

K.V.R Sir 11am JSE { public static void main(String args[]) { HashSet hs=new HashSet(); System.out.println("size="+hs.size()); System.out.println("content="+hs);//[] //add the data hs.add(new Integer(100)); hs.add(new Integer(1)); hs.add(new Integer(10)); hs.add(new Integer(90)); hs.add(new Integer(100)); //duplicate values doesn't allowed System.out.println("content="+hs);//[...] //retriveing data Iterator itr=hs.iterator(); int s=0; while(itr.hasNext()) { Object obj=itr.next(); System.out.println(obj); Integer io=(Integer)obj; int x=io.intValue(); s=s+x;

32

K.V.R Sir 11am JSE } System.out.println("sum="+s); } } /*OUTPUT

C:\>java hset size=0 content=[] content=[1, 100, 10, 90] 1 1 100 100 10 10 90 90 sum=201 */

P) Write a java program which illustrates the concept of TreeSet. import java.util.*; class hset

33

K.V.R Sir 11am JSE { public static void main(String args[]) { TreeSet hs=new TreeSet(); System.out.println("size="+hs.size()); System.out.println("content="+hs);//[] //add the data hs.add(new Integer(100)); hs.add(new Integer(1)); hs.add(new Integer(10)); hs.add(new Integer(90)); hs.add(new Integer(100)); //duplicate values doesn't allowed System.out.println("content="+hs);//[...] //retriveing data Iterator itr=hs.iterator(); int s=0; while(itr.hasNext()) { Object obj=itr.next(); System.out.println(obj); System.out.println(obj); Integer io=(Integer)obj; int x=io.intValue();

34

K.V.R Sir 11am JSE s=s+x;

} System.out.println("sum="+s); } }

/*OUTPUT C:\>java hset size=0 content=[] content=[1, 10, 90, 100] 1 1 10 10 90 90 100 100 sum=201 P) Write a Java program which takes input from keyboard and sort numbers. import java.util.*; class TypeWrap

35

K.V.R Sir 11am JSE { public static void main(String args[]) { TreeSet hs=new TreeSet(); System.out.println("size="+hs.size()); System.out.println("content="+hs);//[] //add the data Scanner s=new Scanner(System.in); System.out.println("Enter first number"); hs.add(new Integer(s.nextInt())); System.out.println("Enter second number"); hs.add(new Integer(s.nextInt())); System.out.println("Enter third number"); hs.add(new Integer(s.nextInt())); System.out.println("Enter fourth number"); hs.add(new Integer(s.nextInt())); System.out.println("Enter fifth number"); hs.add(new Integer(s.nextInt()));

//duplicate values doesn't allowed System.out.println("content="+hs);//[...] //retriveing data } }

36

K.V.R Sir 11am JSE P) Write a Java Program which illustrate the concept of TreeSet by using first(), last(), headset(), tailSet(), subset(). import java.util.*; class Jdbcpro4 { public static void main(String args[]) { TreeSet ts=new TreeSet(); ts.add(10); ts.add(20); ts.add(30); ts.add(40); ts.add(50); ts.add(60); ts.add(70); ts.add(80);

System.out.println("head Set="+ts.headSet(20)); System.out.println("tail Set="+ts.tailSet(70)); System.out.println("First element="+ts.first()); System.out.println("Last element="+ts.last()); System.out.println("Subset="+ts.subSet(30,60)); } } /*OUTPUT
37

K.V.R Sir 11am JSE

C:\>java Jdbcpro4 head Set=[10] tail Set=[70, 80] First element=10 Last element=80 Subset=[30, 40, 50] */ 2D Collection Framework: A 2D Collection Framework variable is one in which the data is organizing in the form of (key,value). In the (key,value) the value of key Should be distinct/unique and value of value may be unique or not that means duplicates are allowed. In the (key, value) both the (key,value) will be treated internally as objects of java.lang.Object EX: Standard Attendance Register 1 2 3 Bhargav Siva Bhargav

EX2: Deposit 10 20 30 54 11.5 45

Here Student Attendance Register and deposit are called 2D Collection Framework variables or map variables. In Student Attendance variables (1,2,3) are called keys (Bhargav, Siva, Bhargav) are called values. In order to deal with 2D C.F.W programming we need to learn interfaces and classes which are present in java.util.*;

38

K.V.R Sir 11am JSE 2D Collection Framework Process: 2D Collection Framework process contains two phases they are 1. Grouping/Assembling phase 2. Ungrouping/Deassesmbling phase.

The following diagram gives sequence steps for both assembling and deassembling phases.

Internally all the entries of 2D Collection Framework variables are treated as mobj belongs to java.lang.Object

III Add wrapper class Object1 and wrapper class Object2 to 2D Collection Framework variable.

IV Retrieve all the entries of 2D Collection Framework variables and hold them in mobj of java.lang.Object V

II

Convert Fundamental value1 and Fundamental value2 into wrapper class object1 and wrapper class Object2.

39

mobj contains kobj and vobj kobj and vobj belong to the java.lang.Object Separate kobj and vobj from mobj.

K.V.R Sir 11am JSE

VI Convert kobj and vobj into wrapper class Object1 and Object2

Fundamental value1 given as key value.

Fundamental value2 is given as value of value.

Convert wrapper class Object1 into fundamental value1

Convert wrapper class Object2 into fundamental value2

VII

Conclusion: In the above diagram steps I,II,II are used for grouping phase and the steps IV,V,VI,VII are used for un grouping or de assembling phase. In order to deal with 2D Collection Framework programming we must import java.util.* which contains collection interfaces and classes. 2D Collection Framework interfaces: 2D Collection Framework interfaces are divided into three types they are 1. 2. 3. 1. i. java.util.Map java.util.Map.Entry java.util.SortedMap java.util.Map: Map is one of the top most interface present in 2D Collection Framework. An object of map interface organizes the data in the form of (key,value). ii. Map interface Object displays the data in random order but not in sorted order. iii. That means whatever order the data is entered in the Map interface Obejct in the same order the data will be displayed. iv. Map interface Object allows us to add data only at end. Profile: 1. public int size(): This method is used for determining the number of entries available in 2D Collection Framework.

40

K.V.R Sir 11am JSE 2. public boolean isEmpty(): This method returns true in the case of 2D Collection Framework is not contains any elements(empty) otherwise it returns false. 3. public boolean put(Object kobj,Object vobj): i. This method is used for both for inserting of 2D Collection Framework variable whatever the (key,value) we decided to place in 2D Collection Framework variable. ii. If the key value already present then the value of value will modify the existing value and it will be considered as modified entry. In this case this method returns false. iii. In the key value is not present in the 2D Collection Framework variable then it will be considered as inserted entry. In this case this method returns false. I) m.put(new Integer(10), new Integer(3.5f)); II) m.put(new Integer(10),new Float(3.5f)); III) m.put(new Integer(30),new Float(4.5)); 12.5 2.5 3.5 4.5

10 20 30

IV) m.put(new Integer(10),new Float(12.5f)); System.out.println(m); //{(10=12.5),(20=3.5),(30=4.5)} In the adove example the statements I,II,III represents inserted entries and the statement IV represents modified entry. 4. public Object get(Object kobj): This method is used for obtaining value of value by passing value of key. EX: Object vobj=m.get(new Integer(10));
1.5

System.out.println(vobj);//1.5 Object vobj1=m.get(new Integer(100));


null

System.out.println(vobj);//null m

41

K.V.R Sir 11am JSE 10 20 30 10.5 3.5 3.5 5. public void remove(Object kobj): This method is used to remove Object from Collection frameword. EX: hm.remove(new Integer(3)) 6. public Set entrySet(): This method is used for extracting or retrieving the entries of 2D Collection Framework variables and hold them in the Object of java.util.Set interface. EX: System.out.println(m); //{(10=1.5),(20=2.5),(30=1.5)} entrySet Iterator() 10 20 30 m 1.5 3.5 1.5

Set s=m.entrySet() //s={(10=1.5),(20=2.5),(30=1.5)} Iterator itr=s.iterator(); While(itr.hasNext()) { Object mobj=itr.next(); //4th Map.Entry me=(Map.Entry)mobj; Object kob=me.getkey(); Object vobj=me.getValue(); Integer io=(Integer)mobj; Integer fo=(Float)vobj Int accno=io.intValue();
42

//5

//6

K.V.R Sir 11am JSE Float bal=fo.floatValue(); System.out.println(bal+is bal of+accno); } EX:2 EntrySet() Set toArray() System.out.println(m);//{(10=1.5),(20=20.5),(30=1.5)} Object mobj[]=toArray(); For(int i=0;i<mobj.length;i++) { Map.Entry me=(Map.Entry)mobj[i]; Object kobj=me.getKey(); Object vobj=me.getValue(); Integer io=(Integer) kobj; Float kobj=(Float) vobj int accno=io.intValue(); float bal=io.floatValue(); System.out.println(bal+is the balance of+accno); } 7. public set keyset(): This method is used for retrieving set of keys of any 2D Collection Framework variable and pass the set of keys to get() and we will get set of value of values. EX: System.out.println(m); //{(10=1.5),(20=2.5),(30=3.5)} Set s=m.getSet(); Iterator itr=s.iterator(); While(itr.hasNext())
43

K.V.R Sir 11am JSE { Object kobj=itr.next(); Object vobj=m.get(kobj); Integer io=(Integer) kobj; Float fo=(Float) vobj; int accno=io.intValue(); float bal=fo.floatValue(); System.out.println(bal+is value of +accno);

Another pattern System.out.println(m); //{(10=1.5),(20=2.5),(30=3.5)} //hset() toArray() Set s=m.keySet(); //s={10,20,30} Object kobj[]=so.toArray(); For(int i=0;i<kobj.length;i++) { Object vobj=m.get(kobj[i]); Integer io=(Integer)kobj[i]; Float fo=(Float)vobj; int accno =io.intValue(); float bal=fo.floatValue(); System.out.println(bal+is the value of+accno); } ii)java.util.Map.Entry: Map is one of the predefined interface. Entry is one of the predefined class defined in Map interface.
44

K.V.R Sir 11am JSE The purpose of Map.Entry is to separate kobj, vobj from any 2D Collection Framework variable. Methods: 1. public Object getKey() 2. public Object getValue() The above methods are used for separating key Object and value Object from any 2D Collection Framework variable.

iii) java.util.SortedMap: 1. SortedMap is one of the sub interface of Map so that Map methods are inherited into SortedMap. 2. An Object of SortedMap allows us to store the data in the form of (key,value). 3. SortedMap interface Object displays the data in Sorted Order sorting can done based on value of key. In the previous versions of Java SortedMap does not contain any special methods except Map methods. 4. In the recent versions of Java SortedMap contains special methods even though Map and SortedMap methods are same, Map methods are defined in some predefined class in such a way that unique elements are allowed and they are displaying in random orger where as SortedMap methods are defined some other predefined class in such a way that unique elements are allowed and they are displayed in sorted order. Methods: 1. 2. 3. 4. 5. Public Object first() Public Object last() Public SotedMap headMap(Object obj) xi<=kobj Public SortedMap subMap(Object obj1,Object obj2) kobj1<=xi<kobj2 Public SortedMap tailMap(Object obj) xi>kobj

45

K.V.R Sir 11am JSE

10 SortedMap 1.5 hm=sm.headMap(new Integer(30));

20

2.5

30 40

3.5 1.5

SortedMap hm=sm.subMap(new Integer(40),new Integer(60))

50

3.5

60

2.5

SortedMap hm=sm.tailMap(New Integer(70)


70 1.5

80

2.5

P) Write a Java program which illustrate HashMap and TreeMap import java.util.*;

46

K.V.R Sir 11am JSE class practicedemo { public static void main(String args[]) { HashMap hm=new HashMap(); System.out.println("content="+hm); System.out.println("size="+hm.size()); //add the data to 2D Collection Framework variable hm.put(new Integer(1), new Float(1.5f)); hm.put(new Integer(10), new Float(2.5f)); hm.put(new Integer(90),new Float(2.5f)); hm.put(new Integer(1),new Float(5.5f)); hm.add(new Integer(54), new Float(6.6f)); hm.remove(new Integer(3)) System.out.print("conent="+hm); System.out.println("size="+hm.size()); //extract the data from 2D Colelction Framework variable System.out.println("using entryset()-------> set--------=> iterator()"); Set s=hm.entrySet(); Iterator itr=s.iterator(); while(itr.hasNext()) { Object mobj=itr.next(); Map.Entry me=(Map.Entry)mobj;

47

K.V.R Sir 11am JSE Object kobj=me.getKey(); Object vobj=me.getValue(); Integer io=(Integer)kobj; Float fo=(Float)vobj; int accno=io.intValue(); float bal=fo.intValue(); System.out.println(bal+"is bal of "+accno); } System.out.println("using keyset()------->set---------->toArray()"); Set s1=hm.keySet();

Object kobj1[]=s1.toArray();

for(int i=0;i<kobj1.length;i++) { Object vobj1=hm.get(kobj1[i]); Integer io1=(Integer)kobj1[i]; Float fo1=(Float)vobj1; int accno1=io1.intValue(); float bal1=fo1.floatValue(); System.out.println(accno1+"-------->"+bal1); } } }

48

K.V.R Sir 11am JSE EX2: import java.util.*; class cfwpra { public static void main(String args[]) { //HashMap hm=new HashMap(); TreeMap hm=new TreeMap(); System.out.println("content="+hm); System.out.println("size="+hm.size()); hm.put(10,1.5); hm.put(20,3.5); hm.put(30,4.5); hm.put(40,2.4); hm.put(50,1.1); Object mobj2=hm.headMap(20); Object mobj3=hm.tailMap(40); Object mobj4=hm.subMap(20,40);

System.out.println("Head map is="+mobj2); System.out.println("Tail map is="+mobj3); System.out.println("sub map is="+mobj4);

System.out.println("size="+hm.size());

49

K.V.R Sir 11am JSE

System.out.println("The first element is="+hm.get(10));

Set s=hm.entrySet(); Iterator itr=s.iterator(); while(itr.hasNext()) { Object mobj=itr.next(); Map.Entry me=(Map.Entry)mobj;

Object kobj=me.getKey(); Object vobj=me.getValue();

Integer io=(Integer)kobj; int i=io.intValue(); System.out.println("Account no="+i);

Double fo=(Double)vobj; double f=fo.doubleValue(); System.out.println("Balance is="+f); } Set s1=hm.keySet();

Object kobj1[]=s1.toArray();

50

K.V.R Sir 11am JSE

for(int i=0;i<kobj1.length;i++) { Object vobj1=hm.get(kobj1[i]); Integer io1=(Integer)kobj1[i]; Double fo1=(Double)vobj1; int accno1=io1.intValue(); double bal1=fo1.doubleValue(); System.out.println(accno1+"-------->"+bal1);

} } }

/* OUTPUT content={} size=0 Head map is={10=1.5} Tail map is={40=2.4, 50=1.1} sub map is={20=3.5, 30=4.5} size=5 The first element is=1.5 Account no=10 Balance is=1.5

51

K.V.R Sir 11am JSE Account no=20 Balance is=3.5 Account no=30 Balance is=4.5 Account no=40 Balance is=2.4 Account no=50 Balance is=1.1 10-------->1.5 20-------->3.5 30-------->4.5 40-------->2.4 50-------->1.5 */

2D Collection Framework Classes: 2D Collection Framework classes contain definitions for those abstract methods which are inherited from 2D Collection Framework interfaces. The following table gives 2D Collection Framework interface names corresponding 2D Collection Framework class names and their hierarchy.

Interfacename

Classname

Hierarchy

1. Map 1. AbstractMap impl Map 2. Map.Entry ----------------------------------------------------------------------52

K.V.R Sir 11am JSE 3. SortedMap 2. AbstractSortedMap extends AbstractMap 3.HashMap extends AbstractMap 4. TreeMap extends AbstractSortedMap In the above hierarchy chart the classes1 and 2 are predefined classes and they are reserved by the SUN Micro System for the future inventions in 2D Collection Framework. So that there is no direct usage of these classes in our real world applications.

The Classes 3 and 4 are the bottom most 2D Collection Framework concrete classes in industry we use these classes for implementations of 2D Collection Framework based applications. The classes 1 and 2 are acting as a middle layer between 2D Collection Framework class Concrete class names. Q) Differences between HashMap and TreeMap. HashMap 1. An Object of HashMap allows the key in unique format. 2. HashMap Object allows the data in the form of (key, value) and sorted in hash table by following hashing mechanism. 3. We cant determine in which order HashMap Object displays the data. That is undetermined format. 4. The operations like insertion, deletion and modification takes more time 5. The retrieval time of HashMap is more 6. Creting HashMap is nothing but creating an Object of HashMap class. HashMap hm=new HashMap(); TreeMap 1. An Object of TreeMap allows the key in unique format. 2. TreeMap Object allows the data in the form of (key, value) in nodes by following binary tree concept. 3. TreeMap always displays data in Sorted format. 4. The operations like insertion, deletion and modification takes less time 5. The retrieval time of TreeMap is less 6. Creting TreeMap is nothing but creating an Object of TreeMap class. TreeMap tm=new TreeMap();

Map Abstract Map Hash Map Abstract Map


53

Map

SortedMap

K.V.R Sir 11am JSE

AbstractSortedMap TreeMap

Legacy Collection Framework: 1. We know that in the older versions of Java the concept of Collection Framework is known as Datastructures. 2. The concept of Datastructures was able to few services to the industry requirements and not able to provide other services to the industry requirements. Later on the current versions of Java the concept of Datastructures re reengineered by SUN Microsystem and released to the industry on the name of new Collection Framework 3. In the current versions of Java Datastructures concept renamed as Legacy Collection Framework and released form of Datastructures is known as new Collection Framework. 4. In order to deal with Legacy Collection Framework we must predefined package called java.util.*. 5. Legacy Collection Framework also contains two types of Collection Frameworks those are i) 1D/single Collection Framework. ii 2D/Double Collection Framework. 6. All the classes and interfaces are belongs to Synchronized that is whatever the data we place in the objects of Legacy Collection Framework variables, that data can be accessed sequentially. EX: Every individual information or personal information which is suitable to one client such type of information to be accessed by only one time at a time. So that we will keep such data into Legacy Collection Framework variables. 7. *All the classes or interfaces of new Collection Framework belong to non Synchronized classes/interfaces provides concurrent access. In general the common information related group of people to be placed in new Collection Framework classes and interfaces for obtaining concurrent access. 8. The following classes used for developing Legacy Collection Framework based applications. i. Java.util.Enumerator ii. Java.util.Vector iii. Java.util.Stack iv. Java.util.Dictionary v. Java.util.HashTable vi. Java.util.Properties i. Java.util.Enumeration:
54

K.V.R Sir 11am JSE 1. Enumeration is one of the predefined interface present in java.util.* package. An object of Enumeration interface is always used for extracting the data from any Legacy Collection Framework variable in forward direction. 2. The functionality of Enumeration is more or less similar to Iterator interface but Enumeration interface Object belongs to synchronize and Iterator interface Object belongs to non Synchronized. 3. When we create an Object of enumerator interface it points out just before the first element. Methods: 1. Public boolean hasMoreElements() 2. Public Object nextElement() Method 1 returns true provided an Object of enumeration is having more elements otherwise it returns false. Method2 is used for obtaining next element of any Legacy Collection Framework variable with respective enumeration interface Object provided method1 returns true must. While(en.hasMoreElements()) { Object obj=en.nextElement(); System.out.println(obj); } ii. java.util.Vector: 1. Vector is one of the predefined concrete class. 2. Creating vector is nothing but creating an Object of Vector class. EX: Vector v=new Vector(); The default capacity of Vector class Object is 10 and default size of Vector class is 0. Capacity always represents the number of cells already created in Vector class Object and size represents the number of programmer defined values. Vector class Object organizes the data in the form of cells and they will be processed internally based on indexing concept. In general the functionality of Vector class is more or less similar to ArrayList but Vector class Object synchronized and ArrayList belongs to non Synchronized. Vector class profile: Constructors: 1. Vector()
55

K.V.R Sir 11am JSE 2. Vector(int size) Instance methods: 3. Public boolean isEmpty() 4. Public void addElement(Object) 5. Public void addElement(int) 6. Public Object removeElement(int) 7. Public void removeElement(Object) 8. Public Object get(int) 9. Public Enumeration elements() 10. Public int size() 11. Public int capacity() Method 5 is used to add elements sequential manner that means if a Vector contains 3 elements we can add at third position only. Method 8 is used for extracting or retrieving the elements from any 1D Legacy Collection Framework. EX: Enumeration en=v.elements(0; While(en.hasMoreElements()) { Object obj=en.nextElement(); Systm.out.println(obj); } P) Write a java program which illustrate the concept of Vector? import java.util.*; class practicedemo { public static void main(String args[]) { Vector v=new Vector();

56

K.V.R Sir 11am JSE System.out.println("contenet="+v); System.out.println("Capacity="+v.capacity()); System.out.println("size="+v.size()); //add elements v.addElement(new Integer(10)); v.addElement(new Float(10.75f)); v.addElement(new Character('A')); System.out.println("capacity="+v.capacity()); System.out.println("size="+v.size()); System.out.println("content="+v); //extracting elements from vector System.out.println("using enumeration"); Enumeration en=v.elements(); while(en.hasMoreElements()) { Object obj=en.nextElement(); System.out.println(obj); } } } EX:2 import java.util.*; class practicedemo {

57

K.V.R Sir 11am JSE public static void main(String args[]) { Vector v=new Vector(); v.addElement(10); v.addElement(new Integer(11)); v.addElement(13); v.addElement(50); System.out.println("the elements present in Vecror="+v); v.addElement("Siva"); System.out.println(v); v.removeElement("Siva"); System.out.println(v); System.out.println(v.size()); System.out.println(v.capacity()); System.out.println("The element at first position="+v.get(1)); System.out.println("The vector v is now="+v); Enumeration en=v.elements(); int s=0; while(en.hasMoreElements()) { Object obj=en.nextElement(); Integer i=(Integer)obj; int k=i.intValue(); s=s+k;

58

K.V.R Sir 11am JSE } System.out.println("The sum is ="+s); Object obj2[]=v.toArray(); System.out.println("The Object elements are"); for(int i=0;i<obj2.length;i++) { System.out.println(obj2[i]); } } } P) Write a program which illustrates Vector by Object Array? import java.util.*; class prt { public static void main(String args[]) { Vector v=new Vector(); System.out.println("contenet="+v); System.out.println("Capacity="+v.capacity()); System.out.println("size="+v.size()); //add elements v.addElement(new Integer(10)); v.addElement(new Integer(20)); v.addElement(20);

59

K.V.R Sir 11am JSE System.out.println("capacity="+v.capacity()); System.out.println("size="+v.size()); System.out.println("content="+v); //extracting elements from vector System.out.println("using enumeration"); Enumeration en=v.elements(); int s=0; while(en.hasMoreElements()) { Object obj=en.nextElement(); Integer io=(Integer)obj; int x=io.intValue(); s=s+x; } System.out.println(s); Object obj1[]=v.toArray(); for(int i=0;i<obj1.length;i++) { System.out.println("The Object Array values are"+ obj1[i]); } } } 3. java.util.Stack(): 1. Stack is one of the sub class of Vector so that all the methods inherited into Stack. Creating a stack is nothing but creating an Object of Stack.
60

K.V.R Sir 11am JSE Stack s=new Stack(); S

2. The size of the Stack can be expandable depends on the incoming flow of the data the working principle of Stack is LIFO (Last in First Out). The element which is inserted last is that element is taken out first. In Stack the data is organized in the form of cells. Real world implementation of Stack: 1. To evaluate the normal function calls during the program execution. 2. To evaluate the expressions that is converting infix expression into either postfix or prefix expression. 3. To evaluate recursive function calls. The following diagram gives positional view of the Stack.

Stack Relative Stack Absolute Position position 4 3


10

Array Absolute positions 0

Array Relative Positions 1

2
20

30

40

61

K.V.R Sir 11am JSE

System.out.println(s); Associativity 10 20 30 40 Internally all the elements of stack are processed based on Stack Absolute positions or Stack relative positions. Profile of Stack Class: 1. Constructor: i. Stack() 2. Instance methods ii. Public boolean empty() iii. Public void push(object) iv. Public Object pop() v. Public Object peek() vi. Public int Search(Object) Constructor1 is used for creating an Object of Stack class. EX: Stack s=new Stack(); Method2 returns true provided stack does not contain any elements otherwise it returns false. Method3 is used for inserting an element into the Stack. Method4 is used for removing the top most element by following Stack absolute positions. Method5 is used for obtaining top most element of the Stack based on the Stack absolute positions. Method6 is used for searching an element into Stack if an element is found in the Stack then this method returns Stack relative position. If the element is not found in the Stack then it returns -1. Hence the result of search method is positive then the search is successful. If the search is negative (-1) then search is un successful. P) Write a java program which illustrates the concept of Stack. import java.util.*; class practicedemo {

62

K.V.R Sir 11am JSE public static void main(String args[]) { Stack s=new Stack(); System.out.println("contennt="+s); System.out.println("size="+s.size()); //0 System.out.println("is empty="+s.empty()); //true //add the data to Stack s.push(new Integer(10)); s.push(new Integer(20)); s.push(new Integer(30)); s.push(new Integer(40)); System.out.println("content="+s); System.out.println("size="+s.size()); System.out.println("is empty="+s.empty()); //delete an element from Stack System.out.println("deleted element="+s.pop()); System.out.println("content after pop="+s); //print top most numbers of the Stack System.out.println("top most elements="+s.peek()); System.out.println("content after peek=+s"); //search an element in Stack int res=s.search(new Integer(10)); System.out.println("Stack relative position of 10="+res); res=s.search(new Integer(100));

63

K.V.R Sir 11am JSE System.out.println("Stack relative position of 100="+res); } } EX:2 import java.util.*; class practicedemo { public static void main(String args[]) { Stack s=new Stack(); System.out.println(s.empty()); System.out.println(s); s.push(10); s.push(2); s.push(14); s.push(29); s.push("siva"); System.out.println("the searched element"+s.search(10)); //This will give stack relative position. System.out.println("The elements in Stack are="+s); s.pop(); System.out.println ("The elements in Stack are="+s); System.out.println ("the top most element is="+s.peek()); int res=s.search(new Integer(10)); System.out.println(res);
64

K.V.R Sir 11am JSE Enumeration en=s.elements(); int s1=0; while(en.hasMoreElements()) { Object op=en.nextElement(); Integer io=(Integer)op; int sp=io.intValue(); s1=s1+sp; } System.out.println("sum is="+s1); System.out.println("The Array Elements are"); Object obj1[]=s.toArray(); for(int i=0;i<obj1.length;i++) { System.out.println(obj1[i]); } } } Java.util.Dictionary: 1. Dictionary is one of the predefined abstract Class of 2D Legacy Collection Framework. An Object of dictionary class organizes the data in the form of (key, value) 2. Since it is an abstract class whose direct usage is not present in real world applications. By making use of sub classes of dictionary (HashTable) we deal with 2D Legacy Collection Framework programming. 3. The functionality of dictionary class object belongs to synchronized and Map interface Object belongs to non synchronized. In general dictionary class acts as background in role in providing the functionality to both HashTable and properties and properties class.
65

K.V.R Sir 11am JSE Profile: Instance Methods: 1. 2. 3. 4. 5. 6. Public int size() Public boolean isEmpty() Public boolean put(Object kobj, Object vobj) Public Object get(Object kobj) Public void remove(Object kobj) Public enumeration keys() Method 6 is used for extracting or retrieving the set of keys from any 2D Legacy Collection Framework variable and place these set of key values to get() for obtaining set of values.

Java.util.HashTable: Hashtable is one of the sub class of the dictionary so that all the methods of dictionary are inherited into Hashtable. Hashtable class Object organizes in the form of (key, value) by following hashing mechanism. Since it is following Hashing mechanism, we cant determine in which order Hashtable class Object displays the data. That is undetermined form. Profile: 1. Hashtable() 2. Hashtable(int size) 3. Hashtable(int size, float loadratio) -----------------fill ratio 1. Hashtable() It is used for creating an Object of Hashtable without specifying any size that is only one cell will be created and it will be expandable depends on incoming flow of data. Hashtable ht=new Hashtable (); ht

i.

As and when the numbers of entries are placed in Hashtable class Object, internally after entries arrived into the main memory. ii. After some considerable amount of time an entry will be created to the existing Hashtable class Object for placing(key, value). This type of memory allocation is known as Late memory allocation(Memory will be allocated after the entry arrived. 2. Hashtable(int size): This constructor is used for creating an Object of Hashtable by specifying number of initial entries to be created and their size can be expandable depends on the incoming flow of the data. That means before the entries are arrived the
66

K.V.R Sir 11am JSE memory space is already created this type of allocation is known as advanced memory allocation. ht EX: Hashtable ht=new Hashtable(4); 3. Hashtable(int size, float loadratio): This constructor is used for creating an Object of Hashtable class by specifying the size and load ratio for achieving the concept of Prememory allocation(Memory space for the entry will be created when the entry is about to enter into the main memory. The purpose of Prememory allocation is to restructure the size of the Hashtable for placing the new entries. When we use this constructor, the number of entries in Hashtable is equal to the size of the Hashtable then JVM will automatically calls the Prememory allocation formula for restricting the size of the Hashtable. Size of the Hashtable=size+ size*load ratio ( This bracket is Ceil bracket This bracket is floor bracket)

Load ratio values are 0.0 to 1.0 (default value is 0.25) Hashtable ht=new Hashtable(4,0.25); ht 1 2 3 4 1.5 2.5 3.1 1.5

Here the number of entries in ht is equal to its size. Then JVM will automatically calls the Prememory allocation formula. Size of ht=4+ 4*0.25

4+1.0=5 ht

67

K.V.R Sir 11am JSE 1 1.5 2 2.5 3 3.1 4 1.5 --------------------------------------------Prememory allocation cell Similarly in the above ht the number of entries once again equal to its size. So that JVM calls Prememory allocation formula. Size of ht= 5+5*0.25 5+ 1.25 5+2=7

ht 1 1.5 2 2.5 3 3.1 4 1.5 -------------------------------------------------------------------------------------------------------------------------------------

Prememory allocation Q) What are the differences between HashMap and Hashtable? HashMap 1. HashMap is one of the non Synchronized class. 2. An Object of HashMap allows null values for (key, value). Hashtable 1. Hashtable is one of the synchronized class. 2. An Object of Hashtable never allows null values for (key, value).

P) Write a Java program to implement the following.


68

K.V.R Sir 11am JSE State Ap Kar TN MH Validations: 1. Pass the state from command prompt and display capital. 2. If state is not found display No IDEA. 3. If state is not entered from command prompt display Please enter state. Assume the above Data to be accessed sequentially in any application. Capital Hyd Ban Chn Mum

import java.util.*; class practicedemo { public static void main(String args[]) { Hashtable ht=new Hashtable(); //add the states and capitals ht.put("AP","HYD"); ht.put(new String("KAR"), new String("BAN")); ht.put("TN","CHN"); ht.put("MH","MUM"); System.out.println("--------------"); Enumeration en=ht.keys(); while(en.hasMoreElements())

69

K.V.R Sir 11am JSE { Object kobj=en.nextElement(); Object vobj=ht.get(kobj); System.out.println(kobj+" "+vobj); } System.out.println("--------------"); if(args.length==0) { System.out.println("please enter the state"); } else { String state=args[0].toUpperCase(); Object cap=ht.get(state); if(cap!=null) { System.out.println(cap+"is capital of "+state); } else { System.out.println("NO IDEA"); } } }

70

K.V.R Sir 11am JSE }

/*OUTPUT javac practicedemo.java java practicedemo kar KAR BAN TN CHN MH MUM AP HYD -------------BAN is capital of KAR */ Limitations of the Hashtable: 1. Hashtable class Object is unable to read from properties/ resource bundle file. 2. Hashtable unable to read the data Environmental variables (Path, classpath). 3. Hashtable Object not allowing us to develop flexible applications. Java.util.Properties: Properties is one of the sub class of Hashtable so that all the methods of Hashtable are inherited into properties class also organizes the user defined data in the form of (key, value) creating properties is nothing but creating Object of properties class. EX: Properties p=new Properties(); Advantages of Properties Class: If we use class as a part of our application development we get the following additional advantages. 1. Properties class Object is able to read the data from properties file/resource bundle file. 2. Properties class Object is able to read the data from Environmental variables(Path, Class Path) 3. With the help of properties Class Object we are able to develop flexible applications. Q) Define properties/resource bundle file?
71

K.V.R Sir 11am JSE A) Properties file is one in which the data is organizing in the form of (key, value). EX: Student.prop/student.rbf Student no Sname Marks =1000 =Sathya ==99.9

Here (student no, sname, marks) are called keys or properties names, (1000,Sathya, 99.99) are called values. Property files always resides in secondary memory and it must be saved some file name with an extension .prop or .rbd Flexibility: 1. Changing the data from properties file then that wont affect Java program that means without touching the source code we can change the data. 2. If Client would like to change the Database at any time thats not a problem just changing one line source code we can connect to any type of Databases. Profile of Properties class: Constructors: 1. Properties() Instance methods: 2. Public void load(FileInputStream) 3. Public String getProperty(String) Constructor1 is used for creating an Object of properties class. EX: Properties p=new properties(); Here p resides in the heap memory. Method2 is used for loading or transferring the content of properties file into Properties class Object from secondary memory by opening the properties file in read mode with the help of FileInputStream class. FileInputStream fs=new FileInputStream(student.prop); FileInputStram is one of the predefined class present in a package called java.io.*. If the properties file not present in secondary memory we get a predefined exception called

72

K.V.R Sir 11am JSE FileNotFoundException. If it is found then it will open successfully in read mode and pointed by an Object of InputStream class. Student.prop --------------------------------------p.load(fis) Method3 is used for obtaining the values (Property values) by passing property names or keys from properties class Object. String sno=p.getProperty(stno); String sname=p.getProperty(sname); String marks=p.getProperty(Marks); System.out.println(Student no=+sno); System.out.println(Student name=+sname); Steps/ Guidelines for reading the data from properties file: 1. Create properties file in any text editor (Edit plus, Net Beans) and save it on some file name with an extension either .prop or .rbf. 2. Create an Object of properties class (residing in heap memory). 3. Open the properties in read mode with the help of InputStream class. 4. Load or transfer the content of properties file from secondary memory into properties class Object 5. Obtain property values or values by passing property names or keys and display those values on the console. 6. Close the property file which was opened in read mode. P) Write a program which illustrates the concept of reading the data from the properties class. Creation of .prop or .rbf files: Go to Netbeans Take other file in creation give file name as iss.prof once and iss.rbf once. Save it in the driver where ever java is available.
73

K.V.R Sir 11am JSE Note: If we do it in notepad it wont work. We have to do it in netbeans or Editplus. sno=10 name=siva marks=100

import java.util.*; import java.io.*; class practicedemo { public static void main(String args[]) { try { //step-1 //properties are already created //step-2 Properties p=new Properties(); //step-3 FileInputStream fis=new FileInputStream(args[0]); //step-4 p.load(fis); //Step-6 String sno=p.getProperty("sno"); String name=p.getProperty("name"); String marks=p.getProperty("marks");

74

K.V.R Sir 11am JSE System.out.println("Student number="+sno); System.out.println("Student name="+name); System.out.println("Student marks="+marks); } catch(FileNotFoundException fe) { System.err.println("file not available"); } catch(ArrayIndexOutOfBoundsException ae) { System.err.println("Please enter property file name"); } catch(Exception e) { System.err.println(e); } } } } P) Write a java program which will read the data from environmental variables of the System import java.util.*; class practicedemo { public static void main(String args[])
75

K.V.R Sir 11am JSE { Properties p=System.getProperties(); System.out.println("--------------"); Enumeration en=p.keys(); while(en.hasMoreElements()) { Object evn=en.nextElement(); Object evv=p.get(evn); System.out.println(evn+" "+evv); } } } Scanner Class: Scanner Class is one of the predefined class which is present in java.util.* package. The basic aim of Scanner Class is to read the data automatically from the keyboard. Profile: Constructor: Scanner(Input Stream): This Constructor is used for creating an Object of Scanner Class by passing an Object of InputStream Class. An Object of InputStream class called in created in System class as static data member. The purpose of in gives control of keyboard. EX: Scanner s=new Scanner(System.in) At any point of time an Object of Scanner class allows us to read only one type of values but not multiple values. Instance Methods: 2.public xxx nextXxx(): 3.public String nextLine():

76

K.V.R Sir 11am JSE In the method 2 Xxx represents any fundamental data type. Method 2 is always used for reading any fundamental value from the keyboard. Method3 is used for reading any type of value in the form of String irrespective of its type. P) Write a Java program which will accept two numbers from the keyboard and compute their sum. import java.util.*; class DataRead { public static void main(String args[]) { Scanner s=new Scanner(System.in); System.out.println("enter first number"); String s1=s.nextLine(); System.out.println("enter Second number"); String s2=s.nextLine(); int res=Integer.parseInt(s1)+Integer.parseInt(s2); System.out.println("sum="+res); } } Generics: Generics is a facility developed by SUN Microsystem supplied as part of JDK 1.5 onwards Generics allows variable containing various Data types for avoiding compile time problems. Advantage: 1. It is widely used in Collection Framework because Collection framework allows different types. So by using generics we can avoid the compile time complexity. 2. It eliminate explicit type casting in Collection Framework. 3. It will show errors in compile time rather than runtime.
77

K.V.R Sir 11am JSE

EX: class first<T> { T a; T b; void first(T x, T y) { a=x; b=y; } void display() { System.out.println(a+" "+b); } } class sturec { public static void main(String args[]) { first f=new first(); f.first("siva",8); f.display();

78

K.V.R Sir 11am JSE } /*OUTPUT siva 8 */

79

You might also like