COLLECTIONS
COLLECTIONS
The Collection in Java is a framework that provides an architecture to store and manipulate
the group of objects.
The Collection framework represents a unified architecture for storing and manipulating a group
of objects. It has:
Iterator interface
Iterator interface provides the facility of iterating the elements in a forward direction only.
1 public boolean hasNext() It returns true if the iterator has more elements otherwise it 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.
Iterator<T> iterator()
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.
void clear(), etc. which are implemented by all the subclasses of Collection interface.
List Interface
List interface is the child interface of Collection interface. It inhibits a list type data structure in
which we can store the ordered collection of objects. It can have duplicate values.
List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.
Java ArrayList
Java ArrayList class uses a dynamic array for storing the elements. It is like an array, but there
is no size limit. We can add or remove elements anytime.
It implements the List interface so we can use all the methods of the List interface here. The
ArrayList maintains the insertion order internally.
• Java ArrayList gets initialized by the size. The size is dynamic in the array list, which varies
according to the elements getting added or removed from the list.
The Java ArrayList class extends AbstractList class which implements the List interface. The
List interface extends the Collection and Iterable interfaces in hierarchical order.
ArrayList class declaration
Constructors of ArrayList
Constructor Description
ArrayList(Collection<? extends It is used to build an array list that is initialized with the
E> c) elements of the collection c.
ArrayList(int capacity) It is used to build an array list that has the specified
initial capacity.
Methods of ArrayList
Method Description
void add(int index, E element) It is used to insert the specified element at the specified
position in a list.
boolean add(E e) It is used to append the specified element at the end of a list.
boolean addAll(int index, It is used to append all the elements in the specified
Collection<? extends E> c) collection, starting at the specified position of the list.
void clear() It is used to remove all of the elements from this list.
import java.util.*;
public class ArrayListExample1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Mango");//Adding object in arraylist
list.add("Apple");
list.add("Banana");
list.add("Grapes");
//Printing the arraylist object
System.out.println(list);
}
}
Output:
import java.util.*;
public class ArrayListExample2{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("C");//Adding object in arraylist
list.add("C++");
list.add("PYTHON");
list.add("JAVA");
//Traversing list through Iterator
Iterator itr=list.iterator();//getting the Iterator
while(itr.hasNext()){//check if iterator has the elements
System.out.println(itr.next());//printing the element and move to next
}
}
}
Output:
C
C++
PYTHON
JAVA
import java.util.*;
public class ArrayListExample3{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("C");//Adding object in arraylist
list.add("C++");
list.add("PYTHON");
list.add("JAVA");
//Traversing list through for-each loop
for(String fruit:list)
System.out.println(fruit);
}
}
Output:
C
C++
PYTHON
JAVA
1. import java.util.*;
public class ArrayListExample4{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
al.add("Mango");
al.add("Apple");
al.add("Banana");
al.add("Grapes");
//accessing the element
System.out.println("Returning element: "+al.get(1));//it will return the 2nd element, because index s
tarts from 0
//changing the element
al.set(1,"Dates");
//Traversing list
for(String fruit:al)
System.out.println(fruit);
}
}
Output
Returning element: Apple
Mango
Dates
Banana
2. Grapes
The java.util package provides a utility class Collections, which has the static method sort().
Using the Collections.sort() method, we can easily sort the ArrayList.
import java.util.*;
class SortArrayList{
public static void main(String args[]){
//Creating a list of fruits
List<String> list1=new ArrayList<String>();
list1.add("Mango");
list1.add("Apple");
list1.add("Banana");
list1.add("Grapes");
//Sorting the list
Collections.sort(list1);
//Traversing list through the for-each loop
for(String fruit:list1)
System.out.println(fruit);
System.out.println("Sorting numbers...");
//Creating a list of numbers
List<Integer> list2=new ArrayList<Integer>();
list2.add(21);
list2.add(11);
list2.add(51);
list2.add(1);
//Sorting the list
Collections.sort(list2);
//Traversing list through the for-each loop
for(Integer number:list2)
System.out.println(number);
}
Output:
Apple
Banana
Grapes
Mango
Sorting numbers...
1
11
21
51
Output:
101 Sonoo 23
102 Ravi 21
103 Hanumat 25
Java LinkedList class uses a doubly linked list to store the elements. It provides a linked-list
data structure.
Method Description
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ravi
Vijay
Ravi
Ajay
Output:
ArrayList LinkedList
1) ArrayList internally uses a dynamic array to store the LinkedList internally uses a doubly linked list to
elements. store the elements.
2) Manipulation with ArrayList is slow because it Manipulation with LinkedList is faster than
internally uses an array. If any element is removed from ArrayList because it uses a doubly linked list, so no
the array, all the other elements are shifted in memory. bit shifting is required in memory.
3) An ArrayList class can act as a list only because it LinkedList class can act as a list and queue both
implements List only. because it implements List and Deque interfaces.
4) ArrayList is better for storing and accessing data. LinkedList is better for manipulating data.
5) The memory location for the elements of an ArrayList is The location for the elements of a linked list is not
contiguous. contagious.
6) Generally, when an ArrayList is initialized, a default There is no case of default capacity in a LinkedList.
capacity of 10 is assigned to the ArrayList. In LinkedList, an empty list is created when a
LinkedList is initialized.
7) To be precise, an ArrayList is a resizable array. LinkedList implements the doubly linked list of the
list interface.
Note:
The following are some important points to remember regarding an ArrayList and LinkedList.
o When the rate of addition or removal rate is more than the read scenarios, then go for the
LinkedList. On the other hand, when the frequency of the read scenarios is more than the
addition or removal rate, then ArrayList takes precedence over LinkedList.
o Since the elements of an ArrayList are stored more compact as compared to a LinkedList;
therefore, the ArrayList is more cache-friendly as compared to the LinkedList. Thus,
chances for the cache miss are less in an ArrayList as compared to a LinkedList.
Generally, it is considered that a LinkedList is poor in cache-locality.
Java List
List in Java provides the facility to maintain the ordered collection. It contains the index-based
methods to insert, update, delete and search the elements. It can have the duplicate elements also.
We can also store the null elements in the list.
The List interface is found in the java.util package and inherits the Collection interface.
Method Description
void add(int index, E element) It is used to insert the specified element at the specified
position in a list.
boolean addAll(int index, It is used to append all the elements in the specified
Collection<? extends E> c) collection, starting at the specified position of the list.
void clear() It is used to remove all of the elements from this list.
Method Description
void add(int index, E element) It is used to insert the specified element at the specified
position in a list.
boolean add(E e) It is used to append the specified element at the end of a list.
void clear() It is used to remove all of the elements from this list.
}
}
We can convert the Array to List by traversing the array and adding the element in list one by
one using list.add() method.
import java.util.*;
public class ArrayToListExample{
public static void main(String args[]){
//Creating Array
String[] array={"Java","Python","PHP","C++"};
System.out.println("Printing Array: "+Arrays.toString(array));
//Converting Array to List
List<String> list=new ArrayList<String>();
for(String lang:array){
list.add(lang);
}
System.out.println("Printing List: "+list);
}
}
Output:
There are various ways to sort the List, here we are going to use Collections.sort() method to
sort the list element. The java.util package provides a utility class Collections which has the
static method sort().
import java.util.*;
class SortArrayList{
public static void main(String args[]){
//Creating a list of fruits
List<String> list1=new ArrayList<String>();
list1.add("Mango");
list1.add("Apple");
list1.add("Banana");
list1.add("Grapes");
//Sorting the list
Collections.sort(list1);
//Traversing list through the for-each loop
for(String fruit:list1)
System.out.println(fruit);
System.out.println("Sorting numbers...");
//Creating a list of numbers
List<Integer> list2=new ArrayList<Integer>();
list2.add(21);
list2.add(11);
list2.add(51); list2.add(1);
//Sorting the list
Collections.sort(list2);
//Traversing list through the for-each loop
for(Integer number:list2)
System.out.println(number);
}
Output:
Apple
Banana
Grapes
Mango
Sorting numbers...
1
11
21
51
ListIterator Interface is used to traverse the element in a backward and forward direction.
Method Description
void add(E e) This method inserts the specified element into the list.
boolean hasNext() This method returns true if the list iterator has more elements while traversing the list in the
forward direction.
E next() This method returns the next element in the list and advances the cursor position.
int nextIndex() This method returns the index of the element that would be returned by a subsequent call to
next()
boolean This method returns true if this list iterator has more elements while traversing the list in
hasPrevious() the reverse direction.
E previous() This method returns the previous element in the list and moves the cursor position
backward.
E previousIndex() This method returns the index of the element that would be returned by a subsequent call to
previous().
void remove() This method removes the last element from the list that was returned by next() or
previous() methods
void set(E e) This method replaces the last element returned by next() or previous() methods with the
specified element.
System.out.println("index:"+itr.nextIndex()+" value:"+itr.next());
}
System.out.println("Traversing elements in backward direction");
while(itr.hasPrevious()){
System.out.println("index:"+itr.previousIndex()+" value:"+itr.previous());
}
}
}
Output:
Output:
JDBC
JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the
query with the database. It is a part of JavaSE (Java Standard Edition). JDBC API uses JDBC
drivers to connect with the database. There are four types of JDBC drivers:
o Native Driver,
o Thin Driver
We can use JDBC API to access tabular data stored in any relational database. By the help of
JDBC API, we can save, update, delete and fetch data from the database. It is like Open
Database Connectivity (ODBC) provided by Microsoft.
The java.sql package contains classes and interfaces for JDBC API. A list of
popular interfaces of JDBC API are given below:
o Driver interface
o Connection interface
o Statement interface
o PreparedStatement interface
o CallableStatement interface
o ResultSet interface
o ResultSetMetaData interface
o DatabaseMetaData interface
o RowSet interface
o DriverManager class
o Blob class
o Clob class
o Types class
Why Should We Use JDBC?
Before JDBC, ODBC API was the database API to connect and execute the query with the
database. But, ODBC API uses ODBC driver which is written in C language (i.e. platform
dependent and unsecured). That is why Java has defined its own API (JDBC API) that uses
JDBC drivers (written in Java language).
We can use JDBC API to handle database using Java program and can perform the following
activities:
What is API?
API (Application programming interface) is a document that contains a description of all the
features of a product or software. It represents classes and interfaces that software programs can
follow to communicate with each other.
JDBC Driver is a software component that enables java application to interact with the database.
There are 4 types of JDBC drivers:
The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-
ODBC bridge driver converts JDBC method calls into the ODBC function calls. This is now
discouraged because of thin driver.
Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends that you use
JDBC drivers provided by the vendor of your database instead of the JDBC-ODBC Bridge.
Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle
recommends that you use JDBC drivers provided by the vendor of your
database instead of the JDBC-ODBC Bridge.
Advantages:
o easy to use.
o can be easily connected to any database.
Disadvantages:
o Performance degraded because JDBC method call is converted into the
ODBC function calls.
o The ODBC driver needs to be installed on the client machine.
2) Native-API driver
The Native API driver uses the client-side libraries of the database. The driver converts JDBC method
calls into native calls of the database API. It is not written entirely in java.
Advantage:
Disadvantage:
The Network Protocol driver uses middleware (application server) that converts JDBC calls
directly or indirectly into the vendor-specific database protocol. It is fully written in java.
Advantage:
o No client side library is required because of application server that can perform many
tasks like auditing, load balancing, logging etc.
Disadvantages:
4) Thin driver
The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is
why it is known as thin driver. It is fully written in Java language.
Advantage:
Disadvantage:
There are 5 steps to connect any java application with the database using JDBC. These steps are
as follows:
o Create connection
o Create statement
o Execute queries
o Close connection
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
.Class.forName("oracle.jdbc.driver.OracleDriver");
The getConnection() method of DriverManager class is used to establish connection with the database.
The createStatement() method of Connection interface is used to create statement. The object of
statement is responsible to execute queries with the database.
The executeQuery() method of Statement interface is used to execute queries to the database. This method
returns the object of ResultSet that can be used to get all the records of a table.
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
By closing connection object statement and ResultSet will be closed automatically. The close()
method of Connection interface is used to close the connection.
To connect java application with the oracle database, we need to follow 5 following steps. In
this example, we are using Oracle 10g as the database.
1. Driver class: The driver class for the oracle database
is oracle.jdbc.driver.OracleDriver.
4. Password: It is the password given by the user at the time of installing the oracle
database.
Create a Table
Before establishing connection, create a table in oracle database. Following is the SQL query to
create a table.
In this example, we are connecting to an Oracle database and getting data from emp table.
Here, system and oracle are the username and password of the Oracle database.
import java.sql.*;
class OracleCon{
public static void main(String args[]){
try{
//step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");
}
}
To connect Java application with the MySQL database, we need to follow 5 following steps.
1. Driver class: The driver class for the mysql database is com.mysql.jdbc.Driver.
4. Password: It is the password given by the user at the time of installing the mysql
database. In this example, we are going to use root as the password.
create a table in the mysql database, but before creating table, we need to create database
first.
create database sonoo;
use sonoo;
create table emp(id int(10),name varchar(40),age int(3));
import java.sql.*;
class MysqlCon{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/sonoo","root","root");
//here sonoo is database name, root is username and password
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
DriverManager class
The DriverManager class is the component of JDBC API and also a member of
the java.sql package. The DriverManager class acts as an interface between users and drivers. It
keeps track of the drivers that are available and handles establishing a connection between a
database and the appropriate driver. It contains all the appropriate methods to register and
deregister the database driver class and to create a connection between a Java application and the
database.
Methods of the DriverManager Class
Method Description
2) public static synchronized is used to deregister the given driver (drop the
void deregisterDriver(Driver driver from the list) with DriverManager. If the
driver): given driver has been removed from the list, then
no action is performed by the method.
5) public static Driver Those drivers that understand the mentioned URL
getDriver(String url) (present in the parameter of the method) are
returned by this method provided those drivers are
mentioned in the list of registered drivers.
Connection interface
1) public Statement createStatement(): creates a statement object that can be used to execute
SQL queries.
3) public void setAutoCommit(boolean status): is used to set the commit status. By default, it
is true.
4) public void commit(): saves the changes made since the previous commit/rollback is
permanent.
5) public void rollback(): Drops all changes made since the previous commit/rollback.
6) public void close(): closes the connection and Releases a JDBC resources immediately.
Statement interface
The Statement interface provides methods to execute queries with the database. The statement
interface is a factory of ResultSet i.e. it provides factory method to get the object of ResultSet.
1) public ResultSet executeQuery(String sql): is used to execute SELECT query. It returns the
object of ResultSet.
2) public int executeUpdate(String sql): is used to execute specified query, it may be create,
drop, insert, update, delete etc.
3) public boolean execute(String sql): is used to execute queries that may return multiple
results.
4) public int[] executeBatch(): is used to execute batch of commands.
ResultSet interface
The object of ResultSet maintains a cursor pointing to a row of a table. Initially, cursor points to
before the first row.
1) public boolean next(): is used to move the cursor to the one row next from the
current position.
2) public boolean previous(): is used to move the cursor to the one row previous from
the current position.
3) public boolean first(): is used to move the cursor to the first row in result set
object.
4) public boolean last(): is used to move the cursor to the last row in result set
object.
5) public boolean absolute(int row): is used to move the cursor to the specified row number
in the ResultSet object.
6) public boolean relative(int row): is used to move the cursor to the relative row number in
the ResultSet object, it may be positive or negative.
7) public int getInt(int is used to return the data of specified column index of
columnIndex): the current row as int.
8) public int getInt(String is used to return the data of specified column name of
columnName): the current row as int.
9) public String getString(int is used to return the data of specified column index of
columnIndex): the current row as String.
PreparedStatement interface
Method Description
public void setInt(int paramIndex, int sets the integer value to the given parameter
value) index.
public void setString(int paramIndex, sets the String value to the given parameter
String value) index.
public void setFloat(int paramIndex, sets the float value to the given parameter
float value) index.
public void setDouble(int sets the double value to the given parameter
paramIndex, double value) index.
public int executeUpdate() executes the query. It is used for create, drop,
insert, update, delete etc.
The metadata means data about data i.e. we can get further information from the data.
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.
Method Description
public String getTableName(int index)throws it returns the table name for the
SQLException specified column index.
Syntax
public ResultSetMetaData getMetaData()throws SQLException
The ACID properties describes the transaction management well. ACID stands for Atomicity,
Consistency, isolation and durability.
Consistency ensures bringing the database from one consistent state to another consistent state.
Durability means once a transaction has been committed, it will remain so, even in the event of
errors, power loss etc.
fast performance It makes the performance fast because database is hit at the time of commit.
In JDBC, Connection interface provides methods to manage transaction.
Method Description
con.commit();
con.close();
}}