Chapter 4.
Collections
Mr. Ramdas Biradar
NR Classes
(BCS,BCA,MCM)
Pune-30
Call us @ 8796064387
[Link]/nrclasses
Collections in Java
•Collections in java is a framework that provides an
architecture to store and manipulate the group of objects.
•All the operations that you perform on a data such as
searching, sorting, insertion, manipulation, deletion etc. can
be performed by Java Collections.
•Java Collection simply means a single unit of objects. Java
Collection framework provides many interfaces (Set, List,
Queue, Deque etc.) and classes (ArrayList, Vector,
LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet
etc).
What is Collection in java
• Collection represents a single unit of objects i.e. a group.
• What is framework in java
• provides readymade architecture.
• represents set of classes and interface.
Hierarchy of Collection Framework
The [Link] package contains all the classes and interface for Collection framework.
Methods of Collection interface
Method Description
No.
1 public boolean add(Object element) is used to insert an element in this
collection.
2 public boolean addAll(collection c) is used to insert the specified collection
elements in the invoking collection.
3 public boolean remove(Object is used to delete an element from this
element) collection.
4 public boolean removeAll(Collection c) is used to delete all the elements of
specified collection from the invoking
collection.
5 public boolean retainAll(Collection c) is used to delete all the elements of
invoking collection except the specified
collection.
6 public int size() return the total number of elements in
the collection.
7 public void clear() removes the total no of element
from the collection.
8 public boolean contains(object element) is used to search an element.
9 public boolean containsAll(Collection c) is used to search the specified
collection in this collection.
10 public Iterator iterator() returns an iterator.
11 public Object[] toArray() converts collection into array.
12 public boolean isEmpty() checks if collection is empty.
13 public boolean equals(Object element) matches two collection.
14 public int hashCode() returns the hashcode number for
collection.
•Two ways to iterate the elements of collection in java
• By Iterator interface.
• By for-each loop.
Iterator interface
•Iterator interface provides the facility of iterating the
elements in forward direction only.
•Methods of Iterator interface
•There are only three methods in the Iterator interface. They
are:
•1. public boolean hasNext() : it returns true if iterator has
more elements.
•2. public object next() : it returns the element and moves
the cursor pointer to the next element.
•3. public void remove() : it removes the last elements
returned by the iterator. It is rarely used.
What we are going to learn in Java Collections Framework
–ArrayList class
• LinkedList class
• ListIterator interface
• HashSet class
• LinkedHashSet class
• TreeSet class
• PriorityQueue class
• Map interface
• HashMap class
• LinkedHashMap class
• TreeMap class
• Hashtable class
• Sorting
• Comparable interface
• Comparator interface
Java ArrayList class
•Java ArrayList class uses a dynamic array for storing the
[Link] extends AbstractList class and implements List
interface.
•Java ArrayList class can contain duplicate elements.
•Java ArrayList class maintains insertion order.
•Java ArrayList class is non synchronized.
•Java ArrayList allows random access because array works
at the index basis.
•In Java ArrayList class, manipulation is slow because a lot
of shifting needs to be occurred if any element is removed
from the array list.
Java Non-generic Vs Generic Collection
•Java collection framework was non-generic before JDK 1.5.
Since 1.5, it is generic.
•Java new generic collection allows you to have only one type of
object in collection. Now it is type safe so typecasting is not
required at run time.
•old non-generic example of creating java collection.
•ArrayList al=new ArrayList(); //creating old non-generic arraylist
•new generic example of creating java collection.
•ArrayList<String> al=new ArrayList<String>();
•In generic collection, we specify the type in angular braces. Now
ArrayList is forced to have only specified type of objects in it. If
you try to add another type of object, it gives compile time error.
JDBC Drivers
•Using JDBC drivers enable you to open database
connections and to interact with it by sending SQL or
database commands then receiving results with Java.
•
•JDBC driver implementations vary because of the wide
variety of operating systems and hardware platforms in
which Java operates. Sun has divided the implementation
types into four categories,
–Type 1: JDBC-ODBC Bridge driver (Bridge)
–Type 2: Native-API/partly Java driver (Native)
–Type 3: AllJava/Net-protocol driver (Middleware)
–Type 4: All Java/Native-protocol driver (Pure)
Type 1: JDBC-ODBC Bridge Driver:
•In a Type 1 driver, a JDBC bridge is used to access ODBC
drivers installed on each client machine. Using ODBC
requires configuring on your system a Data Source Name
(DSN) that represents the target database.
•When Java first came out, this was a useful driver because
most databases only supported ODBC access but now this
type of driver is recommended only for experimental use or
when no other alternative is available.
•Java Application → JDBC-ODBC Bridge → ODBC API →
ODBC Driver → Database
Type 1: JDBC-ODBC Bridge Driver:
•Advantage
–The JDBC-ODBC Bridge allows access to almost any
database, since the database's ODBC drivers are already
available.
•Disadvantages
–Since the Bridge driver is not written fully in Java, Type 1
drivers are not portable.
–A performance issue is seen as a JDBC call goes through
the bridge to the ODBC driver, then to the database, and this
applies even in the reverse process. They are the slowest of
all driver types.
–The client system requires the ODBC Installation to use the
driver.
Type 2 : Native-API / partly Java driver
•The distinctive characteristic of type 2 jdbc drivers are that
Type 2 drivers convert JDBC calls into database-specific
calls i.e. this driver is specific to a particular database. Some
distinctive characteristic of type 2 jdbc drivers are shown
below. Example: Oracle will have oracle native api.
Contd..
•Advantage
–The distinctive characteristic of type 2 jdbc drivers are that they
are typically offer better performance than the JDBC-ODBC
Bridge as the layers of communication (tiers) are less than that of
Type
–1 and also it uses Native api which is Database specific.
•Disadvantages
–1. Native API must be installed in the Client System and hence
type 2 drivers cannot be used for the Internet.
–2. Like Type 1 drivers, it’s not written in Java Language which
forms a portability issue.
–3. If we change the Database we have to change the native api
as it is specific to a database
–4. Mostly obsolete now.
Type 3: All Java/Net-protocol driver
•Type 3 database requests are passed through the network
to the middle-tier server. The middle-tier then translates the
request to the database. The middle-tier server can use
Type1, Type 2 or Type 4 drivers.
Contd..
•Advantage
–1. This driver is server-based, so there is no need for any vendor
database library to be present on client machines.
–2. This driver is fully written in Java and hence Portable. It is
suitable for the web.
–3. There are many opportunities to optimize portability,
performance, and scalability.
–4. The net protocol can be designed to make the client JDBC
driver very small and fast to load.
–5. The type 3 driver typically provides support for features such
as caching (connections, query results, and so on), load
balancing, and advanced system administration such as logging
and auditing.
–6. This driver is very flexible allows access to multiple databases
using one driver.
Contd..
•Disadvantage
–It requires another server application to install and maintain.
Traversing the recordset may take longer, since the data comes
through the backend server.
Type 4: Native-protocol / all-Java driver
•The Type 4 uses java networking libraries to communicate
directly with the database server.
•
Contd..
•Advantage
–1. The major benefit of using a type 4 jdbc drivers is that they are
completely written in Java to achieve platform independence and
eliminate deployment administration issues. It is most suitable for
the web.
–2. Number of translation layers is very less i.e. type 4 JDBC
drivers don't have to translate database requests to ODBC or a
native connectivity interface or to pass the request on to another
server, performance is typically quite good.
–3. You don’t need to install special software on the client or
server. Further, these drivers can be downloaded dynamically.
Contd..
•Disadvantage
–With type 4 drivers, the user needs a different driver for each
database.
Which Driver Should be used?
If you are accessing one type of database, such as Oracle, Sybas
JDBC Database Connections
There are 5 steps to connect any java application with the databa
1. Register the driver class
2. Creating connection
3. Creating statement
4. Executing queries
5. Closing connection
1) Register the driver class
•You must register the your driver in your program before you use
it. Registering the driver is the process by which the mysql driver's
class file is loaded into memory so it can be utilized as an
implementation of the JDBC interfaces.
•You need to do this registration only once in your program.
•The forName() method of Class class is used to register the
driver class. This method is used to dynamically load the driver
class.
•Syntax of forName() method
•public static void forName(String className)throws
ClassNotFoundException
•Example to register the mysql class
• [Link]("[Link]");
2) Create the connection with database
•After you've loaded the driver, you can establish a connection
using the [Link]() method.
•The getConnection() method of DriverManager class is used to
establish connection with the database.
•Overloaded [Link]() methods are:
–getConnection(String url)
–getConnection(String url, String user, String password)
Here each form requires a database URL. A database URL is an
address that points to your database.
Cntd..
3) JDBC Statements, PreparedStatement and CallableStatement
•Once a connection is obtained we can interact with the database.
The JDBC Statement, CallableStatement, and
PreparedStatement interfaces define the methods and properties
that enable you to send SQL commands and receive data from
your database.
•This is done using statement object.
How to decide which interface to use
•Statement: This represents the general SQL statement without
parameters. The method createStatement( ) creates a statement
object.
•PreparedStatement : This represents a precompiled sql
statement with or without parameters. PrecompiledStatements
are used for sql commands that need to be executed repeatedly.
The method prepareStatement(string sql) creates a
preparedStatement object.
•CallableStatement : CallableStatement object are used to
execute SQLstored procedures. The method prepareCall(String
sql) creates a callableStatement object.
The Statement Objects:
Creating Statement Object:
•Before you can use a Statement object to execute a SQL
statement, you need to create one using the Connection object's
createStatement( ) method, as in the following example:
•Statement stmt = null;
•try {
• stmt = [Link]( );
• ...
•}
•catch (SQLException e) {
• ...
•}
•Finally { }
4) Execute Queries
using Statement
Once you've created a Statement object, you can then use it to
execute a SQL statement with one of its three execute methods.
•boolean execute(String SQL) : Returns a boolean value of true if
a ResultSet object can be retrieved; otherwise, it returns false if
result is integer. This method is useful when SQL statement
returns multiple resultsets. This occurs generally in stored
procedure.
•int executeUpdate(String SQL) : Returns the numbers of rows
affected by the execution of the SQL statement. Use this method
to execute SQL statements for which you expect to get a number
of rows affected - for example, an INSERT, UPDATE, or DELETE
statement.
•ResultSet executeQuery(String SQL) : Returns a ResultSet
object. Use this method when you expect to get a result set, as
you would with a SELECT statement.
examples
ResultSet rs = [Link](“select * from student”);
int result = [Link](“update studen set class='FY'
where name='xyz');
boolean res = [Link](“drop table if exist roll”);
Closing statement object
•Just as you close a Connection object to save database
resources, for the same reason you should also close the
Statement object.
•A simple call to the close() method will do the job. If you close the
Connection object first it will close the Statement object as well.
However, you should always explicitly close the Statement object
to ensure proper cleanup.
•[Link]( )
Using preparedStatement
•These are used for sql commands that are need to be executed
repeatedly but with different values. These are precompiled
statements.
•SQL command in preparedStatement can contain plceholders
which can be changed at runtime. The placeholders are replaced
by ? In sql command.
•Example:
•PreparedStatement ps = [Link](“update student
set sname=? Where rollno=?”);
•Before the sql statement is executed the placeholder have to be
replaced by actual values.
•This is done by setZZZ(int n,ZZZ v) method. Where ZZZ is
correct type for parameter, Like setString, setInt, setDate etc , n
is the placeholder number and v is the value which replaces the
Example:
PreparedStatement ps = [Link](“insert into Login
values(?,?,?)” );
[Link](1,name);
[Link](2,uname);
[Link](3,pass);
•Now the sql statement can be executed using execute( ),
executeQuery( ) or executeUpdate( ) methods.
Using CallableStatement
•The CallableStatement interface supports stored procedures.
•The Connection class has a prepareCall( ) method to create a
CallableStatement object.
•Example
•CallableStatement cstmt = [Link](“{call
disp_student}”);
•
Process the Result
•A Resultset contains the result of executed query.
•The data is stored in a ResultSet in a tabular format.
•To access these values getString( ), getInt( ) methods.
•You can use it with column name or column number as a
parameter.
•A ResultSet object maintains a cursor which points to its current
row of data.
•
ResultSet Types
•The Default type of a resultset is forward only which means we
can travel only in one direction.
•We can also create a scrollable resultset.
•ResultSet object is associated with statement object the
ResultSet type should be given when the Statement object is
created.
•Syntax:
•Statement st = [Link](int Scrollable, int
concurrencyType)
•The scroll Type indicates how the cursor moves in the ResultSet.
The Concurrency indicates whether the changes made to the
underlying tables by other users are shown in the ResultSet or
not.
•
ResultSet Scroll Types
•1. ResultSet.TYPE_FOWARD_ONLY
•The resultset is nonscrollable. Its cursor moves in forward
direction only from first to last.
•2. ResultSet.TYPE_SCROLL_SENSITIVE
•The resultset is scrollable. Its cursor can move forward or
backward and can be moved to a perticular row. The resultset is
sensitive to the changes made while it is open.
•3. ResultSet.TYPE_SCROLL_INSENSITIVE
•The ResultSet is scrollable. Its cursor can move forward or
backward and can be moved to a perticular row. The resultset is
insensitive to the changes made while it is open.
ResultSet Concurrency
•1. ResultSet.CONCUR_READ_ONLY
•This indicates that a resultset cannot be updated from program.
•2. ResultSet.CONCUR_UPDATEABLE
•This allows a ResultSet to be updated programatically. This
reduces the level of concurrency. Only one user is allowed to
change the data at a time.
•Example:
•st=[Link](ReultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATBLE);
Navigating a Result Set:
•There are several methods in the ResultSet interface that involve
moving the cursor.
•1. public void beforeFirst() throws SQLException
–Moves the cursor to just before the first row
•2. public void afterLast() throws SQLException
–Moves the cursor to just after the last row
•3. public boolean first() throws SQLException
–Moves the cursor to the first row
•4. public void last() throws SQLException
–Moves the cursor to the last row.
•5 public boolean absolute(int row) throws SQLException
–Moves the cursor to the specified row. Absolute(-1) is the last row
Navigating a Result Set:
6. public boolean relative(int row) throws SQLException
–Moves the cursor the given number of rows forward or
backwards from where it currently is pointing.
7. public boolean previous() throws SQLException
–Moves the cursor to the previous row. This method returns false
if the previous row is off the result set
8. public boolean next() throws SQLException
–Moves the cursor to the next row. This method returns false if
there are no more rows in the result set
9. public int getRow() throws SQLException
–Returns the row number that the cursor is pointing to.
10. getXXX(String columnname): XXX represents Int, String,
Float, Short, Long, Time etc.
Navigating a Result Set:
11. public boolean isFirst( )throws SQLException
–Test whether the cursor is at first position.
12. public boolean isLast( )throws SQLException
–Test whether the cursor is at last position.
13. public boolean isBeforeFirst( )throws SQLException
–Test whether the cursor is at beforethe first position.
14. public boolean isBeforeLast( )throws SQLException
–Test whether the cursor is after the last position.
15. close( ) : Disposes the ResultSet.
RowSet
•RowSets are the extensions to ResultSet Interface.
•A RowSet object contains a set of rows from a resultSet.
•It is introduced since JDK 5.
Need of RowSet
•Scrollable ResultSet are very usefull, but database connection
has to be kept open for entire duration.
•This Requires resources.
•The user may not be using the database.
•In such case RowSet is more efficient.
•RowSets can also be used without a database connection.
•Its implementation can be
–RowSets that are connected
–RowSets that are disconnected.
Need of RowSet
•The connected RowSet requires a database connection to be
open.
•A disconnected Rowset gets a connection to a data source,
fills itself with the data and doesnot require the connection ater
that.
•While it is disconnected it doesn't require JDBC Driver or the
full jdbc api.
•It requires very less resources.
The implementation classes of RowSet interface are as follows:
• JdbcRowSet
• CachedRowSet
• WebRowSet
• JoinRowSet or FilteredRowSet
•JdbcRowset:
•A connected rowset that mainly used as a thin wrapper around
a resultset object to make JDBC Driver looks like a JavaBeans
components.
•CahedRowset:
•A disconnected rowset that caches its data in memory. Not
suitable for very large data sets.
The implementation classes of RowSet interface are as follows:
•WebRowSet:
•A connected rowset that uses a HTTP protocol internally to talk
to java servet that provides data access.
•FilteredRowset And JoinRowset:
•Interfaces which supports lightweight operations on row sets
like select and join. These operations are carried out on the
data stored in rowsets, without having to make a database
connection.
Advantages:
• It is easy and flexible to use
• It is Scrollable and Updatable bydefault.
•Disadvantages:
•CachedRowSet cannot hold a large amount of data.
•Disconnected rowset may use older data compared to
connected rowset.
•The changes in the disconnected rowsets do not get updataed
in the database immediately.
Metadata
Metadata means information about data. Some application
need information about the tables, result set or database
dynamically. JDBC provides information about this.
JDBC provides four interfaces using which we can retrieve the
metabase.
–DatabaseMetaData: Gives information about database
–ResultSetMetaData: Gives information about ResultSet object
returned from a database query.
–ParameterMetadata: Gives information about types of
parameters in a prepareStatement object.
–RowSetMetaData: Gives information about structure of a
rowset object.
DatabaseMetaData interface:
•DatabaseMetaData interface provides methods to get meta
data of a database such as database product name, database
product version, driver name, total number of tables, total
number of views etc.
Commonly used methods of DatabaseMetaData interface
•public String getDriverName()throws SQLException: it returns
the name of the JDBC driver.
•public String getDriverVersion()throws SQLException: it
returns the version number of the JDBC driver.
•public String getUserName()throws SQLException: it returns
the username of the database.
•public String getDatabaseProductName()throws
SQLException: it returns the product name of the database.
•public String getDatabaseProductVersion()throws
SQLException: it returns the product version of the database.
•public ResultSet getTables(String catalog, String
schemaPattern, String tableNamePattern, String[] types)throws
SQLException: it returns the description of the tables of the
specified catalog. The table type can be TABLE, VIEW etc.
How to get the object of DatabaseMetaData:
•The getMetaData() method of Connection interface returns the
object of DatabaseMetaData.
•Syntax:
• public DatabaseMetaData getMetaData()throws SQLException
•
•Example:
•DatabaseMetaData dbmt = [Link]( );
ResultSetMetaData Interface
•If you have to get metadata of a table like total number of
column, column name, column type etc. , ResultSetMetaData
interface is useful because it provides methods to get metadata
from the ResultSet object.
•ResultSetMetaData object can be obtained by calling
getMetaData( ) method of ResultSet object
•Example:
•ResultSet rs=[Link]();
•ResultSetMetaData rsmd=[Link]();
Commonly used methods of ResultSetMetaData interface
•public int getColumnCount()throws SQLException
•It returns the total number of columns in the ResultSet object.
•public String getColumnName(int index)throws SQLException
•It returns the column name of the specified column index.
•public String getColumnTypeName(int index)throws
SQLException
•It returns the column type name for the specified index.
•public String getTableName(int index)throws SQLException
•It returns the table name for the specified column index.
Transaction
•A transcation is a group of operations that must behave as if they
are a single.
•Transaction allow you to combine one or more database actions
into single unit.
•If an application needs to execute multiple SQL statements to
fulfill one goal a transaction can be used.
•
Advantages
•Related operation can be combined together and executed as a
single unit.
•Transaction maintains data integrity. Example Banking
transaction.
•It is possible to rollback changes if an exception occurs.
•Multiple changes can be applied as an atomic unit at a commit
time.
•It involves three steps:
–Start the transaction, perform its component operation.
–If all operations are successful commit transaction.
–If one of the operation fails rollback the operation.
Cntd..
•By default the database is autoCommit mode.
•If we are using transaction we have to set autoCommit mode to
false.
•This can be done using setAutoCommit(false)
•When all the operations are done call the commit( ) or the
rollback changes to undo the changes.
•In JDBC, Connection interface provides methods to manage
transaction.
•1. void setAutoCommit(boolean status) It is true bydefault
means each transaction is committed bydefault.
•2. void commit() commits the transaction.
•3. void rollback() cancels the transaction.
•4. getAutoCommit( ) Retrieves the connections auto-commit
Save points
•We can create a save point so that operations are rolled back
only till the save points and to the start of the transaction.
•The connection object is used to create the stave point.
•Example:
•savepoint sp = [Link](“savepoint1”);
•To release a savepoint releaseSavepoint() method is used.
•To rollback to the specific save point, use the rollback method
with the savepoint object as a parameter.
•Example
•[Link]( sp );
Batch Updates
•Instead of executing a single query, we can execute a batch
(group) of queries. It makes the performance fast.
•The Statement and PreparedStatement interfaces provide
methods for batch processing.
•The required methods for batch processing are given below:
•void addBatch(String query) It adds query into batch.
•Int[ ] executeBatch() It executes the batch of queries.
•Note : You can not add SELECT command to batch since it
returns resultSet.
Steps to create batch:
• Load the driver class
• Create Connection
• Create Statement
• Add query in the batch
• Execute Batch
• Close Connection