0% found this document useful (0 votes)
19 views45 pages

Cb2305 Ajp - Unit 5

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views45 pages

Cb2305 Ajp - Unit 5

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 45

UNIT V COLLECTIONS FRAMEWORK & DATABASE CONNECTIVITY

Collections Framework-Autoboxing -For-Each Style for Loop-Collection Interfaces-


Collection Interface-List Interface-Set Interface -Sorted Set Interface-Collection Classes-
Array List Class-LinkedList Class-HashSet Class-LinkedHashSet Class-Tree Set Class-
Enum Set Class-Accessing a Collection via an Iterator-Using an Iterator-The For-Each
Alternative to Iterators-Storing User-Defined Classes in Collections-Working with Maps-The
Map Interfaces-The Map Classes-Arrays- Accessing databases using JDBC connectivity –
DAO

Introduction:
1. An array is an indexed collection of fixed no of homogeneous data elements. (or)
2. An array represents a group of elements of same data type.
3. The main advantage of array is we can represent huge no of elements by using
single variable. So that readability of the code will be improved.

Limitations of Object[] array:


1. Arrays are fixed in size that is once we created an array there is no chance of
increasing (or) decreasing the size based on our requirement hence to use arrays
concept compulsory we should know the size in advance which may not possible
always.
2. Arrays can hold only homogeneous data elements.

Example:
Student[] s=new Student[10000];
s[0]=new Student();//valid
s[1]=new Customer();//invalid(compile time error)
Compile time error:
Test.java:7: cannot find symbol
Symbol: class Customer
Location: class Test
s[1]=new Customer();

3) But we can resolve this problem by using object type array(Object[]).


Example:
Object[] o=new Object[10000];
o[0]=new Student();
o[1]=new Customer();

4) Arrays concept is not implemented based on some data structure hence ready-made
methods support we can't expert. For every requirement we have to write the code
explicitly.

To overcome the above limitations, we should go for collections concept.

1. Collections are growable in nature that is based on our requirement we can


increase (or) decrease the size hence memory point of view collections concept is
recommended to use.
2. Collections can hold both homogeneous and heterogeneous objects.
3. Every collection class is implemented based on some standard data structure
hence for every requirement ready-made method support is available being a
programmer we can use these methods directly without writing the functionality
on our own.

Hierarchy of Collection Framework

Let us see the hierarchy of Collection framework. The java.util package contains all the
classes and interfaces for the Collection framework.

Methods of Collection interface

There are many methods declared in the Collection interface. They are as follows:

No Method Description
.

1 public boolean add(E e) It is used to insert an element in this collection.

2 public boolean It is used to insert the specified collection


addAll(Collection<? extends elements in the invoking collection.
E> c)

3 public boolean remove(Object It is used to delete an element from the collection.


element)
4 public boolean It is used to delete all the elements of the
removeAll(Collection<?> c) specified collection from the invoking collection.

5 default boolean It is used to delete all the elements of the


removeIf(Predicate<? super collection that satisfy the specified predicate.
E> filter)

6 public boolean It is used to delete all the elements of invoking


retainAll(Collection<?> c) collection except the specified collection.

7 public int size() It returns the total number of elements in the


collection.

8 public void clear() It removes the total number of elements from the
collection.

9 public boolean It is used to search an element.


contains(Object element)

10 public boolean It is used to search the specified collection in the


containsAll(Collection<?> c) collection.

11 public Iterator iterator() It returns an iterator.

12 public Object[] toArray() It converts collection into array.

13 public <T> T[] toArray(T[] a) It converts collection into array. Here, the
runtime type of the returned array is that of the
specified array.

14 public boolean isEmpty() It checks if collection is empty.

15 default Stream<E> It returns a possibly parallel Stream with the


parallelStream() collection as its source.

16 default Stream<E> stream() It returns a sequential Stream with the collection


as its source.

17 default Spliterator<E> It generates a Spliterator over the specified


spliterator() elements in the collection.

18 public boolean equals(Object It matches two collections.


element)

19 public int hashCode() It returns the hash code number of the collection.

Iterator interface

Iterator interface provides the facility of iterating the elements in a forward direction only.
Methods of Iterator interface

There are only three methods in the Iterator interface. They are:

No Method Description
.

1 public boolean It returns true if the iterator has more elements otherwise it
hasNext() returns false.

2 public Object next() It returns the element and moves the cursor pointer to the
next element.

3 public void remove() It removes the last elements returned by the iterator. It is
less used.

Iterable Interface

The Iterable interface is the root interface for all the collection classes. The Collection
interface extends the Iterable interface and therefore all the subclasses of Collection interface
also implement the Iterable interface.

It contains only one abstract method. i.e.,

1. Iterator<T> iterator()

It returns the iterator over the elements of type T.

Collection Interface

The Collection interface is the interface which is implemented by all the classes in the
collection framework. It declares the methods that every collection will have. In other words,
we can say that the Collection interface builds the foundation on which the collection
framework depends.

Some of the methods of Collection interface are Boolean add ( Object obj), Boolean addAll
( Collection c), void clear(), etc. which are implemented by all the subclasses of Collection
interface.
Differences between Arrays and Collections

Arrays Collections

1) Arrays are fixed in size. 1) Collections are growable in nature.

2) Memory point of view arrays are not 2) Memory point of view collections are highly
recommended to use. recommended to use.

3) Performance point of view arrays are 3) Performance point of view collections are not
recommended to use. recommended to use.

4) Arrays can hold only homogeneous 4) Collections can hold both homogeneous and
data type elements. heterogeneous elements.

5) There is no underlying data structure 5) Every collection class is implemented based on


for arrays and hence there is no some standard data structure and hence
readymade method support. readymade method support is available.
6) Arrays can hold both primitives and 6) Collections can hold only objects but not
object types. primitives.
Collection:
If we want to represent a group of objects as single entity then we should go for collections.

Collection framework:

It defines several classes and interfaces to represent a group of objects as a single entity.

9(Nine) key interfaces of collection framework:


1. Collection
2. List
3. Set
4. SortedSet
5. NavigableSet
6. Queue
7. Map
8. SortedMap
9. NavigableMap
Collection:

1. If we want to represent a group of "individual objects" as a single entity then we


should go for collection.
2. In general we can consider collection as root interface of entire collection
framework.
3. Collection interface defines the most common methods which can be applicable
for any collection object.
4. There is no concrete class which implements Collection interface directly.

List:
1. It is the child interface of Collection.
2. If we want to represent a group of individual objects as a single entity where
"duplicates are allow and insertion order must be preserved" then we should go
for List interface.

Diagram:

Set:
1. It is the child interface of Collection.
2. If we want to represent a group of individual objects as single entity "where
duplicates are not allow and insertion order is not preserved" then we should go
for Set interface.
Diagram:

SortedSet:
1. It is the child interface of Set.
2. If we want to represent a group of individual objects as single entity "where
duplicates are not allow but all objects will be insertion according to some sorting
order then we should go for SortedSet.
(or)
3. If we want to represent a group of "unique objects" according to some sorting
order then we should go for SortedSet.
NavigableSet:
1. It is the child interface of SortedSet.
2. It provides several methods for navigation purposes.
Queue:
1. It is the child interface of Collection.
2. If we want to represent a group of individual objects prior to processing then we
should go for queue concept.
Diagram:

Note: All the above interfaces (Collection, List, Set, SortedSet, NavigableSet, and
Queue) meant for representing a group of individual objects.
If we want to represent a group of objects as key-value pairs then we should go for Map.
Map:
1. Map is not child interface of Collection.
2. If we want to represent a group of objects as key-value pairs then we should go for
Map interface.
3. Duplicate keys are not allowed but values can be duplicated.
Diagram:

SortedMap:

1. It is the child interface of Map.


2. If we want to represent a group of objects as key value pairs "according to some
sorting order of keys" then we should go for SortedMap.

NavigableMap:
1) It is the child interface of SortedMap and defines several methods for navigation
purposes.

What is the difference between Collection and Collections ?


"Collection is an "interface" which can be used to represent a group of objects as a
single entity. Whereas "Collections is an utility class" present in java.util package to
define several utility methods for Collection objects.
Collection--------------------interface
Collections------------------class

Collection interface:
 If we want to represent a group of individual objects as a single entity then we
should go for Collection interface. This interface defines the most common general
methods which can be applicable for any Collection object.
 The following is the list of methods present in Collection interface.

1. boolean add(Object o);


2. boolean addAll(Collection c);
3. boolean remove(Object o);
4. boolean removeAll(Object o);
5. boolean retainAll(Collection c);
To remove all objects except those present in c.
6. Void clear();
7. boolean contains(Object o);
8. boolean containsAll(Collection c);
9. boolean isEmpty();
10. Int size();
11. Object[] toArray();
12. Iterator iterator();

There is no concrete class which implements Collection interface directly.


List interface:
 It is the child interface of Collection.
 If we want to represent a group of individual objects as a single entity where
duplicates are allow and insertion order is preserved. Then we should go for List.
 We can differentiate duplicate objects and we can maintain insertion order by
means of index hence "index play very important role in List"

List interface defines the following specific methods.


1. boolean add(int index,Object o);
2. boolean addAll(int index,Collectio c);
3. Object get(int index);
4. Object remove(int index);
5. Object set(int index,Object new);//to replace
6. Int indexOf(Object o);
Returns index of first occurrence of "o".
7. Int lastIndexOf(Object o);
8. ListIterator listIterator();

ArrayList:
1. The underlying data structure is resizable array (or) growable array.
2. Duplicate objects are allowed.
3. Insertion order preserved.
4. Heterogeneous objects are allowed.(except TreeSet , TreeMap every where
heterogenious objects are allowed)
5. Null insertion is possible.

Constructors:
1) ArrayList a=new ArrayList();
Creates an empty ArrayList object with default initial capacity "10" if ArrayList
reaches its max capacity then a new ArrayList object will be created with
New capacity=(current capacity*3/2)+1
2) ArrayList a=new ArrayList(int initialcapacity);
Creates an empty ArrayList object with the specified initial capacity.
3) ArrayList a=new ArrayList(collection c);
Creates an equivalent ArrayList object for the given Collection that is this constructor
meant for inter conversation between collection objects. That is to dance between
collection objects.

Demo program for ArrayList:


import java.util.*;
class ArrayListDemo
{
public static void main(String[] args)
{
ArrayList a=new ArrayList();
a.add("A");
a.add(10);
a.add("A");
a.add(null);
System.out.println(a);//[A, 10, A, null]
a.remove(2);
System.out.println(a);//[A, 10, null]
a.add(2,"m");
a.add("n");
System.out.println(a);//[A, 10, m, null, n]
}
}

 Usually we can use collection to hold and transfer objects from one tier to another
tier. To provide support for this requirement every Collection class already
implements Serializable and Cloneable interfaces.
 ArrayList and Vector classes implements RandomAccess interface so that any
random element we can access with the same speed. Hence ArrayList is the best
choice of "retrival operation".
 RandomAccess interface present in util package and doesn't contain any methods.
It is a marker interface.

Getting synchronized version of ArrayList object:


Collections class defines the following method to return synchronized version of
List.
Public static List synchronizedList(list l);

Example

 ArrayList is the best choice if our frequent operation is retrieval.


 ArrayList is the worst choice if our frequent operation is insertion (or) deletion in the
middle because it requires several internal shift operations.

Diagram:

LinkedList:
1. The underlying data structure is double LinkedList
2. If our frequent operation is insertion (or) deletion in the middle then LinkedList is
the best choice.
3. If our frequent operation is retrieval operation then LinkedList is worst choice.
4. Duplicate objects are allowed.
5. Insertion order is preserved.
6. Heterogeneous objects are allowed.
7. Null insertion is possible.
8. Implements Serializable and Cloneable interfaces but not RandomAccess.

Diagram:

Usually we can use LinkedList to implement Stacks and Queues.


To provide support for this requirement LinkedList class defines the following 6 specific
methods.
1. void addFirst(Object o);
2. void addLast(Object o);
3. Object getFirst();
4. Object getLast();
5. Object removeFirst();
6. Object removeLast();
We can apply these methods only on LinkedList object.
Constructors:
1. LinkedList l=new LinkedList();
Creates an empty LinkedList object.
2. LinkedList l=new LinkedList(Collection c);
To create an equivalent LinkedList object for the given collection.

Example:
import java.util.*;
class LinkedListDemo
{
public static void main(String[] args)
{
LinkedList l=new LinkedList();
l.add("ashok");
l.add(30);
l.add(null);
l.add("ashok");
System.out.println(l);//[ashok, 30, null, ashok]
l.set(0,"software");
System.out.println(l);//[software, 30, null,ashok]
l.set(0,"venky");
System.out.println(l);//[venky, 30, null, ashok]
l.removeLast();
System.out.println(l);//[venky, 30, null]
l.addFirst("vvv");
System.out.println(l);//[vvv, venky, 30, null]
}
}
HashSet:
1. The underlying data structure is Hashtable.
2. Insertion order is not preserved and it is based on hash code of the objects.
3. Duplicate objects are not allowed.
4. If we are trying to insert duplicate objects we won't get compile time error and
runtime error add() method simply returns false.
5. Heterogeneous objects are allowed.
6. Null insertion is possible.(only once)
7. Implements Serializable and Cloneable interfaces but not RandomAccess.
8. HashSet is best suitable, if our frequent operation is "Search".
Constructors:
1. HashSet h=new HashSet();
Creates an empty HashSet object with default initial capacity 16 and default fill
ratio 0.75(fill ratio is also known as load factor).
2. HashSet h=new HashSet(int initialcapacity);
Creates an empty HashSet object with the specified initial capacity and default fill
ratio 0.75.
3. HashSet h=new HashSet(int initialcapacity,float fillratio);
4. HashSet h=new HashSet(Collection c);

Note : After filling how much ratio new HashSet object will be created , The ratio is called
"FillRatio" or "LoadFactor".

Example:
import java.util.*;
class HashSetDemo
{
public static void main(String[] args)
{
HashSet h=new HashSet();
h.add("B");
h.add("C");
h.add("D");
h.add("Z");
h.add(null);
h.add(10);
System.out.println(h.add("Z"));//false
System.out.println(h);//[null, D, B, C, 10, Z]
}
}
LinkedHashSet:
1. It is the child class of HashSet.
2. LinkedHashSet is exactly same as HashSet except the following differences.

HashSet LinkedHashSet

1) The underlying data structure 1) The underlying data structure is a combination of


is Hashtable. LinkedList and Hashtable.

2) Insertion order is not


2) Insertion order is preserved.
preserved.

3) Introduced in 1.2 v. 3) Introduced in 1.4v.

In the above program if we are replacing HashSet with LinkedHashSet the output is [B, C,
D, Z, null, 10].That is insertion order is preserved.

Example:
import java.util.*;
class LinkedHashSetDemo
{
public static void main(String[] args)
{
LinkedHashSet h=new LinkedHashSet();
h.add("B");
h.add("C");
h.add("D");
h.add("Z");
h.add(null);
h.add(10);
System.out.println(h.add("Z"));//false
System.out.println(h);//[B, C, D, Z, null, 10]
}
}
Note: LinkedHashSet and LinkedHashMap commonly used for implementing "cache
applications" where insertion order must be preserved and duplicates are not allowed.
SortedSet:
1. It is child interface of Set.
2. If we want to represent a group of "unique objects" where duplicates are not
allowed and all objects must be inserting according to some sorting order then we
should go for SortedSet interface.
3. That sorting order can be either default natural sorting (or) customized sorting
order.
SortedSet interface define the following 6 specific methods.
1. Object first();
2. Object last();
3. SortedSet headSet(Object obj);
Returns the SortedSet whose elements are <obj.
4. SortedSet tailSet(Object obj);
It returns the SortedSet whose elements are >=obj.
5. SortedSet subset(Object o1,Object o2);
Returns the SortedSet whose elements are >=o1 but <o2.
6. Comparator comparator();
o Returns the Comparator object that describes underlying sorting technique.
o If we are following default natural sorting order then this method returns
null.
Diagram:

TreeSet:
1. The underlying data structure is balanced tree.
2. Duplicate objects are not allowed.
3. Insertion order is not preserved and it is based on some sorting order of objects.
4. Heterogeneous objects are not allowed if we are trying to insert heterogeneous
objects then we will get ClassCastException.
5. Null insertion is possible(only once).
Constructors:
1. TreeSet t=new TreeSet();
Creates an empty TreeSet object where all elements will be inserted according to
default natural sorting order.
2. TreeSet t=new TreeSet(Comparator c);
Creates an empty TreeSet object where all objects will be inserted according to
customized sorting order specified by Comparator object.
3. TreeSet t=new TreeSet(SortedSet s);
4. TreeSet t=new TreeSet(Collection c);
Example 1:
import java.util.*;
class TreeSetDemo
{
public static void main(String[] args)
{
TreeSet t=new TreeSet();
t.add("A");
t.add("a");
t.add("B");
t.add("Z");
t.add("L");
//t.add(new Integer(10));//ClassCastException
//t.add(null);//NullPointerException
System.out.println(t);//[A, B, L, Z, a]
}
}
Null acceptance:
 For the empty TreeSet as the 1st element "null" insertion is possible but after
inserting that null if we are trying to insert any other we will get
 NullPointerException.
For the non empty TreeSet if we are trying to insert null then we will get
NullPointerException.

Example 2:
import java.util.*;
class TreeSetDemo
{
public static void main(String[] args)
{
TreeSet t=new TreeSet();
t.add(new StringBuffer("A"));
t.add(new StringBuffer("Z"));
t.add(new StringBuffer("L"));
t.add(new StringBuffer("B"));
System.out.println(t);
}
}
Output:
Runtime Exception.

Note :
 Exception in thread "main" java.lang.ClassCastException: java.lang.StringBuffer
cannot be cast to java.lang.Comparable
 If we are depending on default natural sorting order compulsory the objects should
be homogeneous and Comparable otherwise we will get ClassCastException.
 An object is said to be Comparable if and only if the corresponding class
implements Comparable interface.
 String class and all wrapper classes implements Comparable interface but
 StringBuffer class doesn't implement Comparable interface hence in the above
program we are getting ClassCastException.

EnumSet in Java
Enumerations or popularly known as enum serve the purpose of representing a group of
named constants in a programming language. For example, the 4 suits in a deck of playing
cards may be 4 enumerators named Club, Diamond, Heart, and Spade, belonging to an
enumerated type named Suit.
The EnumSet is one of the specialized implementations of the Set interface for use with
the enumeration type. A few important features of EnumSet are as follows:
 It extends AbstractSet class and implements Set Interface in Java.
 EnumSet class is a member of the Java Collections Framework & is not synchronized.
 It’s a high-performance set implementation, much faster than HashSet.
 All of the elements in an EnumSet must come from a single enumeration type that is
specified when the set is created either explicitly or implicitly.
 It does not allow null Objects and throws NullPointerException if we do so.
 It uses a fail-safe iterator, so it won’t throw ConcurrentModificationException if the
collection is modified while iterating.

The Hierarchy of EnumSet is as follows:

↳ java.util.AbstractCollection<E>
java.lang.Object

↳ java.util.AbstractSet<E>
↳ java.util.EnumSet<E>
Here, E is the type of elements stored.

Syntax: Declaration
public abstract class EnumSet<E extends Enum<E>>
Here, E specifies the elements. E must extend Enum, which enforces the requirement that
the elements must be of the specified enum type.

Methods of EnumSet
Method Action Performed

allOf(Class<E> Creates an enum set containing all of the elements in the


elementType) specified element type.

clone() Returns a copy of this set.

Creates an enum set with the same element type as the specified
complementOf
enum set, initially containing all the elements of this type that are
(EnumSet<E> s)
not contained in the specified set.

copyOf
Creates an enum set initialized from the specified collection.
(Collection<E> c)
Method Action Performed

copyOf Creates an enum set with the same element type as the specified
(EnumSet<E> s) enum set, initially containing the same elements (if any).

noneOf(Class<E>
Creates an empty enum set with the specified element type.
elementType)

of(E e) Creates an enum set initially containing the specified element.

of(E e1, E e2) Creates an enum set initially containing the specified elements.

of(E first, E… rest) Creates an enum set initially containing the specified elements.

of(E e1, E e2, E e3) Creates an enum set initially containing the specified elements.

of(E e1, E e2, E e3,


Creates an enum set initially containing the specified elements.
E e4)

of(E e1, E e2, E e3,


Creates an enum set initially containing the specified elements.
E e4, E e5)

Creates an enum set initially containing all of the elements in the


range(E from, E to)
range defined by the two specified endpoints.

// Java Program to Illustrate Working


// of EnumSet and its functions

// Importing required classes


import java.util.EnumSet;

// Enum
enum Gfg { CODE, LEARN, CONTRIBUTE, QUIZ, MCQ };

// Main class
// EnumSetExample
public class GFG {

// Main driver method


public static void main(String[] args) {

// Creating a set
EnumSet<Gfg> set1, set2, set3, set4;
// Adding elements
set1 = EnumSet.of(Gfg.QUIZ, Gfg.CONTRIBUTE,
Gfg.LEARN, Gfg.CODE);
set2 = EnumSet.complementOf(set1);
set3 = EnumSet.allOf(Gfg.class);
set4 = EnumSet.range(Gfg.CODE, Gfg.CONTRIBUTE);

// Printing corresponding elements in Sets


System.out.println("Set 1: " + set1);
System.out.println("Set 2: " + set2);
System.out.println("Set 3: " + set3);
System.out.println("Set 4: " + set4);
}
}

Output
Set 1: [CODE, LEARN, CONTRIBUTE, QUIZ]
Set 2: [MCQ]
Set 3: [CODE, LEARN, CONTRIBUTE, QUIZ, MCQ]
Set 4: [CODE, LEARN, CONTRIBUTE]

3 cursors of java:

If we want to get objects one by one from the collection then we should go for cursor.
There are 3 types of cursors available in java. They are:

1. Enumeration
2. Iterator
3. ListIterator

Enumeration:

1. We can use Enumeration to get objects one by one from the legacy collection
objects.
2. We can create Enumeration object by using elements() method.
public Enumeration elements();
Enumeration e=v.elements();
using Vector Object

Enumeration interface defines the following two methods

1. public boolean hasMoreElements();


2. public Object nextElement();

Example:
import java.util.*;
class EnumerationDemo
{
public static void main(String[] args)
{
Vector v=new Vector();
for(int i=0;i<=10;i++)
{
v.addElement(i);
}
System.out.println(v);//[0, 1, 2, 3, 4, 5, 6, 7,
8, 9, 10]
Enumeration e=v.elements();
while(e.hasMoreElements())
{
Integer i=(Integer)e.nextElement();
if(i%2==0)
System.out.println(i);//0 2 4 6 8 10
}
System.out.print(v);//[0, 1, 2, 3, 4, 5, 6, 7, 8,
9, 10]
}
}
Limitations of Enumeration:

1. We can apply Enumeration concept only for legacy classes and it is not a universal
cursor.
2. By using Enumeration we can get only read access and we can't perform remove
operations.
3. To overcome these limitations sun people introduced Iterator concept
in 1.2v.

Iterator:

1. We can use Iterator to get objects one by one from any collection object.
2. We can apply Iterator concept for any collection object and it is a universal cursor.
3. While iterating the objects by Iterator we can perform both read and remove
operations.

We can get Iterator object by using iterator() method of Collection interface.


public Iterator iterator();
Iterator itr=c.iterator();

Iterator interface defines the following 3 methods.

1. public boolean hasNext();


2. public object next();
3. public void remove();

Example:
import java.util.*;
class IteratorDemo
{
public static void main(String[] args)
{
ArrayList a=new ArrayList();
for(int i=0;i<=10;i++)
{
a.add(i);
}
System.out.println(a);//[0, 1, 2, 3, 4, 5, 6, 7,
8, 9, 10]
Iterator itr=a.iterator();
while(itr.hasNext())
{
Integer i=(Integer)itr.next();
if(i%2==0)
System.out.println(i);//0, 2, 4, 6,
8, 10
else
itr.remove();
}
System.out.println(a);//[0, 2, 4, 6, 8, 10]
}
}

Limitations of Iterator:

1. Both enumeration and Iterator are single direction cursors only. That is we can
always move only forward direction and we can't move to the backward direction.
2. While iterating by Iterator we can perform only read and remove operations and
we can't perform replacement and addition of new objects.
3. To overcome these limitations sun people introduced listIterator concept.

ListIterator:

1. ListIterator is the child interface of Iterator.


2. By using listIterator we can move either to the forward direction (or) to the
backward direction that is it is a bi-directional cursor.
3. While iterating by listIterator we can perform replacement and addition of new
objects in addition to read and remove operations

By using listIterator method we can create listIterator object.

public ListIterator listIterator();


ListIterator itr=l.listIterator();
(l is any List object)

ListIterator interface defines the following 9 methods.

1. public boolean hasNext();


2. public Object next(); forward
3. public int nextIndex();
4. public boolean hasPrevious();
5. public Object previous(); backward
6. public int previousIndex();
7. public void remove();
8. public void set(Object new);
9. public void add(Object new);

Example:
import java.util.*;
class ListIteratorDemo
{
public static void main(String[] args)
{
LinkedList l=new LinkedList();
l.add("balakrishna");
l.add("venki");
l.add("chiru");
l.add("nag");
System.out.println(l);//[balakrishna, venki,
chiru, nag]
ListIterator itr=l.listIterator();
while(itr.hasNext())
{
String s=(String)itr.next();
if(s.equals("venki"))
{
itr.remove();
}
}
System.out.println(l);//[balakrishna, chiru, nag]
}
}
Case 1:

if(s.equals("chiru"))
{
itr.set("chran");
}
Output:
[balakrishna, venki, chiru, nag]
[balakrishna, venki, chran, nag]

Case 2:

if(s.equals("nag"))
{
itr.add("chitu");
}
Output:
[balakrishna, venki, chiru, nag]
[balakrishna, venki, chiru, nag, chitu]
The most powerful cursor is listIterator but its limitation is it is applicable only for "List
objects".

Iterator vs Foreach in Java


Background :
Iterator is an interface provided by collection framework to traverse a collection and for a
sequential access of items in the collection.

// Iterating over collection 'c' using iterator


for (Iterator i = c.iterator(); i.hasNext(); )
System.out.println(i.next());
For eachloop is meant for traversing items in a collection.

// Iterating over collection 'c' using for-each


for (Element e: c)
System.out.println(e);
We read the ‘:’ used in for-each loop as “in”. So loop reads as “for each element e in
elements”, here elements is the collection which stores Element type items.
elements.forEach (e  System.out.println(e) );

When to use which traversal?

If we have to modify collection, we can use Iterator.

While using nested for loops it is better to use for-each loop, consider the below code for
better understanding.

import java.util.*;

public class Main


{
public static void main(String args[])
{
// Create a link list which stores integer elements
List<Integer> l = new LinkedList<Integer>();

// Now add elements to the Link List


l.add(2);
l.add(3);
l.add(4);

// Make another Link List which stores integer elements


List<Integer> s=new LinkedList<Integer>();
s.add(7);
s.add(8);
s.add(9);
// Iterator to iterate over a Link List
for (Iterator<Integer> itr1=l.iterator(); itr1.hasNext(); )
{
for (Iterator<Integer> itr2=s.iterator(); itr2.hasNext(); )
{
if (itr1.next() < itr2.next())
{
System.out.println(itr1.next());
}
}
}
}
}

Output:

Exception in thread "main" java.util.NoSuchElementException


at java.util.LinkedList$ListItr.next(LinkedList.java:888)
at Main.main(Main.java:29)
The above code throws java.util.NoSuchElementException.

In the above code we are calling the next() method again and again for itr1 (i.e., for List l).
Now we are advancing the iterator without even checking if it has any more elements left in
the collection(in the inner loop), thus we are advancing the iterator more than the number of
elements in the collection which leads to NoSuchElementException.
for-each loops are tailor made for nested loops. Replace the iterator code with the below
code.
// Java program to demonstrate working of nested for-each
import java.util.*;
public class Main
{
public static void main(String args[])
{
// Create a link list which stores integer elements
List<Integer> l=new LinkedList<Integer>();

// Now add elements to the Link List


l.add(2);
l.add(3);
l.add(4);

// Make another Link List which stores integer elements


List<Integer> s=new LinkedList<Integer>();
s.add(2);
s.add(4);
s.add(5);
s.add(6);

// Iterator to iterate over a Link List


for (int a:l)
{
for (int b:s)
{
if (a<b)
System.out.print(a + " ");
}
}
}
}

Output:

22233344

User-Defined Objects in Collections


Collection classes are used to store built in objects such as Integer, String, Character
etc. But the potential of collection classes isn't just restricted to the storage of built-in objects.
Collections classes can store any similar type of objects, be it objects of a built-in class or
objects of an user-defined class. This feature of collection class is very userful when we are
making an application which requires us to store many objects of user-defined classes and not
just objects of built-in classes.
In this example, we have created a Customer class with three instance variables - name,
balance and ID, together they make up an object of Customer class. We are going to use
ArrayList collection class to store objects of this Customer class.
import java.util.*;
class Customer
{
String name;
int balance;
int id;
//Costructor
Customer(String s, int i, int j)
{
name=s;
balance=i;
id=j;
}

//toString() method is overridden to give a meaningful String representaion of each object.


public String toString()
{
return "|Name : "+ name + "|Balance : "+ balance + "|ID : " + id + "|\n";
}
public static void main(String... ar)
{
ArrayList<Customer> arr= new ArrayList<Customer>(); //ArrayList will contain a collection
of Customer's objects.

//Creating Customer objects.


Customer customer1 = new Customer("Jay", 1000, 2);
Customer customer2 = new Customer("Shane", 7000 3);
Customer customer3 = new Customer("Ricky", 5000, 1);
Customer customer4 = new Customer("Tom", 3000, 6);
Customer customer5 = new Customer("Mick", 6000, 4);

//Storing objects in an ArrayList collection class.


arr.add(customer1);
arr.add(customer2);
arr.add(customer3);
arr.add(customer4);
arr.add(customer5);

for(Customer c : arr)
System.out.println(c);

}
}

Map Interface in Java


In Java, Map Interface is present in java.util package represents a mapping between a key
and a value. Java Map interface is not a subtype of the Collection interface. Therefore it
behaves a bit differently from the rest of the collection types. A map contains unique keys.
Maps are perfect to use for key-value association mapping such as dictionaries. The maps
are used to perform lookups by keys or when someone wants to retrieve and update
elements by keys. Some common scenarios are as follows:
 A map of error codes and their descriptions.
 A map of zip codes and cities.
 A map of managers and employees. Each manager (key) is associated with a list
of employees (value) he manages.
 A map of classes and students. Each class (key) is associated with a list of
students (value).
Creating Map Objects
Since Map is an interface, objects cannot be created of the type map. We always need a class
that extends this map in order to create an object. And also, after the introduction of Generics
in Java 1.5, it is possible to restrict the type of object that can be stored in the Map.

Syntax: Defining Type-safe Map

Map hm = new HashMap();


// Obj is the type of the object to be stored in Map

Characteristics of a Map Interface


1. A Map cannot contain duplicate keys and each key can map to at most one value.
Some implementations allow null key and null values like
the HashMap and LinkedHashMap, but some do not like the TreeMap.
2. The order of a map depends on the specific implementations. For
example, TreeMap and LinkedHashMap have predictable orders,
while HashMap does not.
3. There are two interfaces for implementing Map in Java. They are Map
and SortedMap, and three classes: HashMap, TreeMap, and LinkedHashMap.
Methods in Java Map Interface
Method Action Performed

This method is used in Java Map Interface to clear and


clear() remove all of the elements or mappings from a specified
Map collection.

This method is used in Map Interface in Java to check


whether a particular key is being mapped into the Map or
containsKey(Object)
not. It takes the key element as a parameter and returns True
if that element is mapped in the map.

This method is used in Map Interface to check whether a


particular value is being mapped by a single or more than
containsValue(Object) one key in the Map. It takes the value as a parameter and
returns True if that value is mapped by any of the keys in
the map.
Method Action Performed

This method is used in Map Interface in Java to create a set


out of the same elements contained in the map. It basically
entrySet()
returns a set view of the map or we can create a new set and
store the map elements into them.

This method is used in Java Map Interface to check for


equality between two maps. It verifies whether the elements
equals(Object)
of one map passed as a parameter is equal to the elements of
this map or not.

This method is used to retrieve or fetch the value mapped by


get(Object) a particular key mentioned in the parameter. It returns
NULL when the map contains no such mapping for the key.

This method is used in Map Interface to generate a


hashCode()
hashCode for the given map containing keys and values.

This method is used to check if a map is having any entry


isEmpty() for key and value pairs. If no mapping exists, then this
returns true.

This method is used in Map Interface to return a Set view of


the keys contained in this map. The set is backed by the
keySet()
map, so changes to the map are reflected in the set, and
vice-versa.

This method is used in Java Map Interface to associate the


put(Object, Object)
specified value with the specified key in this map.

This method is used in Map Interface in Java to copy all of


putAll(Map)
the mappings from the specified map to this map.

This method is used in Map Interface to remove the


remove(Object)
mapping for a key from this map if it is present in the map.

This method is used to return the number of key/value pairs


size()
available in the map.

This method is used in Java Map Interface to create a


values() collection out of the values of the map. It basically returns a
Collection view of the values in the HashMap.
Method Action Performed

getOrDefault(Object key, Returns the value to which the specified key is mapped, or
V defaultValue) defaultValue if this map contains no mapping for the key

import java.util.*;

// Main class
class GFG {

// Main driver method


public static void main(String args[])
{
// Creating an empty HashMap
Map<String, Integer> hm
= new HashMap<String, Integer>();

// Inserting pairs in above Map


// using put() method
hm.put("a", new Integer(100));
hm.put("b", new Integer(200));
hm.put("c", new Integer(300));
hm.put("d", new Integer(400));

// Traversing through Map using for-each loop


for (Map.Entry<String, Integer> me :
hm.entrySet()) {

// Printing keys
System.out.print(me.getKey() + ":");
System.out.println(me.getValue());
}
}
}
Output:
a:100
b:200
c:300
d:400
AutoBoxing

Wrapper class: It is a class that encapsulates, or "wraps," a primitive data type, allowing it to
be treated as an object.

Primitive Data Types Wrapper classes


byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean

AutoBoxing / Boxing : Boxing refers to the process of converting a primitive data type into
its corresponding wrapper class object.

UnBoxing : Unboxing is the process of extracting the primitive value from a wrapper class
object.

Example Program
public class AutoBoxingExample {
public static void main(String[] args) {
// Auto boxing: int to Integer
int primitiveInt = 42;
Integer wrapperInt = primitiveInt;

// Auto boxing: char to Character


char primitiveChar = 'A';
Character wrapperChar = primitiveChar;

// Auto boxing: boolean to Boolean


boolean primitiveBoolean = true;
Boolean wrapperBoolean = primitiveBoolean;

// Printing the values


System.out.println("Primitive int: " + primitiveInt);
System.out.println("Wrapper Integer: " + wrapperInt);
System.out.println("Primitive char: " + primitiveChar);
System.out.println("Wrapper Character: " + wrapperChar);
System.out.println("Primitive boolean: " + primitiveBoolean);
System.out.println("Wrapper Boolean: " + wrapperBoolean);
}
}
Introduction to JDBC

JDBC stands for Java Database Connectivity, which is a standard Java API for database independent
connectivity between the Java programming language, and a wide range of databases. The JDBC
library includes APIs for each of the tasks mentioned below that are commonly associated with
database usage.

 Making a connection to a database.

 Creating SQL or MySQL statements.

 Executing SQL or MySQL queries in the database.

 Viewing & modifying the resulting records.

Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows for
portable access to an underlying database. Java can be used to write different types of executables,
such as:

 Java Applications

 Java Applets

 Java Servlets

 Java ServerPages (JSPs)

 Enterprise JavaBeans (EJBs).

All of these different executables are able to use a JDBC driver to access a database, and take
advantage of the stored data. JDBC provides the same capabilities as ODBC, allowing Java programs
to contain databaseindependent code. For this purpose, we need an API (Application programming
interface) that ODBC (Open Database Connectivity).

 The ODBC API was the database API to connect and execute queries with the database. But,
ODBC API uses ODBC driver written in C Language (platform dependent and unsecured).
 That is why Java has defined its own API, called JDBC (Java Database Connectivity ), that uses
JDBC drivers ( Written in Java language )
 The JDBC drivers are more compatible with Java applications to provide database
Communications.
 JDBC is a Java API to connect and execute queries with the database. JDBC API uses JDBC
drivers to connect with the database.
 JDBC supports a Wide level of portability, and JDBC is simple and easy to use.
 In JDBC API, a programmer needs a specific driver to Connect to a specific database.

RDBMS Driver
Oracle Oracle.jdbc.driver.OracleDriver
MySQL Com.mysql.jdbc.Driver
SyBase Com.microsoft.jdbc.sqlserver
SQLServer Com.microsft.jdbc.Sqlserver
DB2 Com.ibm.db2.jdbc.net.DB2Driver
List of some popular Drivers
JDBC Architecture

The main function of the JDBC is to provide a standard obstruction for Java applications to
communicate with the database.

The JDBC Architecture

As shown in the figure, the Java application that wants to communicate with a database has to be
programmed using JDBC API.

The JDBC Driver is required to process the SQL requests and generate the results.

The JDBC driver has to play an essential role in the JDBC architecture. The Driver Manager

uses the same specific drivers to connect with specific databases effectively.

JDBC Driver is a software component that enables Java applications to interact with the database.

There are four types of JDBC drivers, those are

1. Type 1 Driver ( JDBC - ODBC bridge driver)

2. Type 2 Driver ( partial JDBC driver)

3. Type 3 Driver ( pure Java driver for middleware )

4. Type 4 Driver ( pure Java driver with direct database connection )


1. Type 1 Driver (JDBC - ODBC bridge driver)

The Type-1 driver acts as a bridge between JDBC and other database connectivity mechanisms such
as ODBC.

The JDBC - ODBC bridge driver converts JDBC method calls into the ODBC method calls.

JDBC – ODBC Bridge Driver

Advantages

 Easy to use
 Can be easily connected to any database.

Disadvantages

 Performance degraded because of a large number of transactions (i.e. JDBC calls to ODBC
calls)
 The ODBC driver needs to be installed on the client machine.

Type -2 Driver (Partial JDBC driver):

The type -2 driver uses the client-side libraries of the database. So, this driver is also called as Native -
API driver.

This driver converts JDBC method calls into native calls of the database API. It is not written entirely
in Java, so it is called as partial JDBC driver.
Native API Driver

Advantages:

 Performance upgraded that JDBC - ODBC bridge driver.


 Suitable to use with server-side applications.

Disadvantages:

 This Native driver needs to be installed on each client machine.


 The vendor client library needs to be installed on the client machine.
 It will increase the cost of the application if the application needs to run on different
platforms.

Type -3 Driver (Pure Java driver for middleware)

The type-3 driver is completely implemented in java; hence it is a pure java JDBC driver.

The type-3 driver uses middleware (application server) that converts JDBC calls directly or indirectly

into the vendor-specific database protocol, so it is called Network protocol driver.


Java Driver for middleware

Advantages:

 No client-side library is required on the client side.


 Pure Java drivers and auto downloadable.

Disadvantages:

 Network support is required on the client machine.


 This driver is costly compared to other drivers.

Type - 4 Driver (Pure Java driver with direct database Connection):

The type-4 driver is a pure Java driver, which converts JDBC calls directly into the vendor-specific
database protocol that is why it is known as thin driver
The Java Thin Server

Advantages

 This driver is a pure Java driver and auto-downloadable.


 Better performance than all other drivers
 No software is required on the client side or server side.

Disadvantage

 Drivers depend on the Database.

Database Programming using JDBC

JDBC APIs are used by a Java application to communicate with a database.

In other words, we use JDBC connectivity code in Java application to communicate with a database.

There are five steps to connect any Java application with the database in java using JDBC. They are as
follows.

Step 1: Register for driver class

Step 2: Creating Connection

Step 3: Creating Statement

Step4: Executing SQL Statements

Step 5: Closing Connection


Step 1: (Register the driver class)

In this step, we register the driver class with driver Manager by using forName () method of Class.

Syntax : Class.forName(Driver Class Name)

Example: Class.forName(“Oracle.jdbc.driver.OracleDriver”);

Step 2: ( Creating Connection )

In this step, we can create a connection with database server by using getConnection() method of
DriverManager class.

Syntax : getConnection(String url, String name, String pwd)

Example: con = DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:xe”, “system”,


“admin”);

Step3: (Creating Statement)

After the connection made, we need to create the statement object to execute the SQL statements.

The CreateStatement() method of the connection interface is used to create a statement. This
statement object is responsible for executing SQL statements with the database.

Syntax: CreateStatement()

Example: Stateent stmt = con.Statement();

Step 4: (Executing SQL Statements)

After the statement object is created, it can be used to execute the SQL Statements by using
executeUpdate() or executeQuery() method of statement interface.

The executeQuery() method is only used to execute SELECT Statements.

Syntax: executeQuery(String query)

executeUpdate(String query)

Example: // using executeQuery()

String query = “Select * from emp”;

Resultset rs = stmt.executeQuery(query);

// using executeUpdate()

String query =”insert into emp values (504, ‘Madhu’, 29)

Stmt.executeUpdate(query);

Step 5: (Closing the Connection)

After executing all the SQL statements and obtaining the results, we need to close the connection
and release the session.

The Close() method of connection interface is used to close the connection.

Syntax: Close()
Example: con.Close();

Connecting with Oracle Database

For connecting java application with the oracle database, we need to know following information to
perform databse connectivity with oracle.

In this example we are using Oracle log as the database, so we need to know following information
for the oracle database.

 Driver Class : The driver class for Oracle database is


“Oracle.jdbc.driver.OracleDriver”
 Connection URL: The connection URL for the oracle log databaseis
“jdbc:oracle:thin:@localhost:1521:xe”

Where jdbc is the API oracle is the databse, thin is the driver, localhost is the server name on which
Oracle is running, 1521 is the port number and XE is the oracle service name.

 Username : The default username for the oracle databse is “system”.


 Password: is given by the user at the time of installing the oracle database.

To connect java application with the oracle databse “ojdbc14.jar” file is required to be loaded.

There are two ways to load the “ojdbc14.jar” file, we need to follow any one of two ways.

1. Paste the “ojdbc14.jar” file in the “java/jre/lib/ext” folder.


2. Set classpath

Firstly, search the “ojdbc14.jar” file then go to “java/jre/lib/ext” folder and paste the jar file here.

(Or)

Set class path: To set classpath, goto environment variable then click on new tab, In variable name
write classpath and in variable value paste the path to “ojdbc14.jar” by appending “ojdbc14.jar”; . ;
as

“C:\oraclexe\app\oracle\product\10.2.0\server\jdbc\lib\ojdbc14.jar; . ;”.

Example:

Let’s first create a table and insert two or more records in oracle database.

SQL> create table emp( id number(10), name varchar2(40), age number(3));

SQL> insert into emp values( 501, ‘Madhu’, 30);

SQL> insert into emp values( 502, ‘Hari’, 31);

SQL> insert into emp values( 503, ‘Ravi’, 32);

Program: Connect java application with Oracle database for selecting or retrieving data.

SelectData.java

import java.sql.*
import java.util.*

class SelectData

public static void main (String args[])

try

// Step 1: load the driver class

Class.forName(“Oracle.jdbc.driver.OracleDriver”);

//Step 2: Create the Connection object

Connection con = DriverManager.getConnection(“jdbc:Oracle:thin:@localhost:1521:xe”, “system”,


“admin”);

// Step 3: create the statement object

Statement stmt = con.CreateStatement();

//Step 4: execute query

ResultSet rs = stmt.executeQuery(“select * from emp”);

while (rs.next())

System.out.println(rs.getInt() + “ “ + rs.getString(2)+rs.getString(3));

// Step 5: close the connection object

con.Close();

Catch(Exception e) { System.out.println(e);}

Program: Connect Java application with Oracle database for inserting data

Insertdata.java

import java.sql.*;

import java.util.*;

class InsertData

{
public static void main(String args[])

try

Class.forName("Oracle.jdbc.driver.OracleDriver");

Conncection con = DriverManager.getConnection("jdbc:Oracle:thin:@localhost:1521:xe","System",


"admin");

Statement stmt = con.Create.Statement();

stmt.executeUpdate("insert into emp values (504,"Ganesh",28)");

System.Out.Println("Inserted...");

con.Close();

catch(Exception e)

System.out.println("Exception is : "+e);

Output:

D:> javac InsertData.java

D:> java InsertData

Inserted....

Program: Java application with Oracle database for updating data.

Updatedata.java

import java.sql.*;

import java.util.*;

class Updatedata
{

public static void main (String args[])

try

Class.forName("Oracle.jdbc.driver.OracleDriver");

Conncection con = DriverManager.getConnection("jdbc:Oracle:thin:@localhost:1521:xe","System",


"admin");

Statement stmt = con.Create.Statement();

stmt.executeUpdate("update emp set age = 38 where id = 503");

System.out.println("Update...");

con.Close();

catch(Exception e)

System.out.println("Exception is : "+e);

Output:

d:> javac Updatedata.java

d:> java Updatedata

Updateted....

Driver Manager Class:

The driver manager class acts as an interface between users and drivers. It keeps track of available
drivers and establishes a connection between a database and the appropriate driver.
DAO Class in Java

Data Access Object or DAO design pattern is a popular design pattern to


implement the persistence layer of Java application. DAO pattern is based
on abstraction and encapsulation design principles. It shields the rest of
the application from any change in the persistence layer e.g. change of
database from Oracle to MySQL, change of persistence technology e.g.
from File System to Database.

Data Access Object patterns, often known as DAO patterns, are used to
divide high level business services from low level data accessing APIs or
actions. The members of the Data Access Object Pattern are listed below.

Data Access Object Interface: The Data Access Object Interface


specifies the common operations to be carried out on a model object (s).

Concrete Data Access Object class: This class implements the


aforementioned interface. This class is in charge of obtaining data from a
data source, which could be a database, XML, or another type of storage
system.

Model or Value Object: This object is a straightforward POJO with


get/set methods for storing data obtained using the DAO class.

Implementation
A student object will be created and used as a model as well as a value
object.

Data Access Object Interface is called StudentDao.

The concrete class StudentDaoImpl implements the Data Access Object


Interface. StudentDao will be used by DaoPatternDemo, our demo class,
to show how to use the Data Access Object pattern.
Step 1:

Value Object creation.

S.java

1. public class S {
2. private String n;
3. private int r;
4.
5. S(String n, int r){
6. this.n = n;
7. this.r = r;
8. }
9.
10. public String getName() {
11. return n;
12. }
13.
14. public void setName(String n) {
15. this.n = n;
16. }
17.
18. public int getRollNo() {
19. return r;
20. }
21.
22. public void setRollNo(int r) {
23. this.r = r;
24. }
25. }

Step 2:

Data Access Object Interface creation.

SD.java

1. import java.util.List;
2. public interface SD {
3. public List<S> getAllStudents();
4. public S getStudent(int r);
5. public void updateStudent(S s);
6. public void deleteStudent(S s);
7. }

Step 3:

Construct a class that implements the aforementioned interface.

SDI.java

1. import java.util.ArrayList;
2. import java.util.List;
3. public class SDI implements SD {
4. // list is working as the database
5. List<S> ss;
6. public SDI(){
7. ss = new ArrayList<S>();
8. S s1 = new S("Sonoo",0);
9. S s2 = new S("Jaiswal",1);
10. ss.add(s1);
11. ss.add(s2);
12. }
13. @Override
14. public void deleteStudent(S s) {
15. students.remove(s.getRollNo());
16. System.out.println(" Student: Roll No " + student.getRollN
o() + ", has been deleted from the database");
17. }
18. // traversing list of students from the database
19. @Override
20. public List<S> getAllStudents() {
21. return ss;
22. }
23. @Override
24. public S getStudent(int r) {
25. return ss.get(r);
26. }
27. @Override
28. public void updateStudent(S s) {
29. ss.get(s.getRollNo()).setName(s.getName());
30. System.out.println(" Student: Roll No " + student.getRollN
o() + ", has been updated in the database");
31. }
32. }

Step 4:

Utilize the StudentDao to illustrate how to use the Data Access Object
pattern.

DPDemo.java

1. public class DPDemo {


2. public static void main(String[] args) {
3. SD sD = new SDI();
4. // print all the students
5. for (S s : sD.getAllStudents()) {
6. System.out.println("Student: [RollNo : " + s.getRollNo() + ", Na
me : " + s.getName() + " ]");
7. }
8. // update student
9. S s =sD.getAllStudents().get(0);
10. s.setName("JavaTpoint");
11. sD.updateStudent(s);
12. //get the student
13. sD.getStudent(0);
14. System.out.println("Student: [RollNo : " + s.getRollNo() + "
, Name : " + s.getName() + " ]");
15. }
16. }

Step 5:

Check the results.

You might also like