0% found this document useful (0 votes)
6 views

Unit 4

The document discusses collections in Java. It defines what a collection is, explains the collection framework hierarchy, and describes common interfaces like Collection, List, and interfaces and classes that implement them like ArrayList, LinkedList.

Uploaded by

sarbjot209
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Unit 4

The document discusses collections in Java. It defines what a collection is, explains the collection framework hierarchy, and describes common interfaces like Collection, List, and interfaces and classes that implement them like ArrayList, LinkedList.

Uploaded by

sarbjot209
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

UNIT-IV

Introduction to JAVA
PCC-CSE-309G
Collections in Java
The Collection in Java is a framework that provides an architecture to store and
manipulate the group of objects.

Java Collections can achieve all the operations that you perform on a data such as
searching, sorting, insertion, manipulation, and deletion.

Java Collection means a single unit of objects. Java Collection framework provides many
interfaces (Set, List, Queue, Deque) and classes (ArrayList,
Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).

What is Collection in Java


A Collection represents a single unit of objects, i.e., a group.

What is a framework in Java


oIt provides readymade architecture.
oIt represents a set of classes and interfaces.
oIt is optional.

What is Collection framework

The Collection framework represents a unified architecture for storing and manipulating a
group of objects. It has:

1.Interfaces and its implementations, i.e., classes


2.Algorithm

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.
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 hasNext() It returns true if the iterator has more elements
otherwis
2 public Object next() It returns the element and moves the cursor pointer to t

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

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.

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. To

instantiate the List interface, we must use :

1.List <data-type> list1= new ArrayList();


2.List <data-type> list2 = new LinkedList();
3.List <data-type> list3 = new Vector();
4.List <data-type> list4 = new Stack();

There are various methods in List interface that can be used to insert, delete, and access
the elements from the list.

The classes that implement the List interface are given below.

ArrayList
The ArrayList class implements the List interface. It uses a dynamic array to store the
duplicate element of different data types. The ArrayList class maintains the insertion order
and is non-synchronized. The elements stored in the ArrayList class can be randomly
accessed. Consider the following example.

1.import java.util.*;
2.class TestJavaCollection1{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();//Creating arraylist
5. list.add("Ravi");//Adding object in arraylist
6. list.add("Vijay");
7. list.add("Ravi");
8. list.add("Ajay");
9. //Traversing list through Iterator
10. Iterator itr=list.iterator();
11.while(itr.hasNext()){
12. System.out.println(itr.next());
13. }
14. }
15. }

Output:

Ravi Vijay Ravi Ajay

LinkedList
LinkedList implements the Collection interface. It uses a doubly linked list internally to
store the elements. It can store the duplicate elements. It maintains the insertion order
and is not synchronized. In LinkedList, the manipulation is fast because no shifting is
required.

Consider the following example.

1.import java.util.*;
2.public class TestJavaCollection2{
3.public static void main(String args[]){
4.LinkedList<String> al=new LinkedList<String>();
5.al.add("Ravi");
6.al.add("Vijay");
7.al.add("Ravi");
8.al.add("Ajay");
9.Iterator<String> itr=al.iterator();
10.while(itr.hasNext()){
11.System.out.println(itr.next());
12. }
13. }
14. }

Output:
Ravi
Vijay Ravi Ajay

LinkedList class declaration


Let's see the declaration for java.util.LinkedList class.

1. public class LinkedList<E> extends AbstractSequentialList<E> implements


List<E>, Deque<E>, Cloneable, Serializable

Constructors of Java LinkedList


Constructor Description

LinkedList() It is used to construct an empty list.

LinkedList(Collection<? extends It is used to construct a list containing the elements of the spe
E> c) they are returned by the collection's iterator.

Methods of Java LinkedList


Method Description

boolean add(E e) It is used to append the specified element to the end o

void add(int index, E element) It is used to insert the specified element at the specifie

boolean addAll(Collection<? extends E> c) It is used to append all of the elements in the specified
list, in the order that they are returned by the specifie
d

boolean addAll(Collection<? extends E> c) It is used to append all of the elements in the specified
list, in the order that they are returned by the specified

boolean addAll(int index, Collection<? It is used to append all the elements in the specified co
extends E> c) specified position of the list.

void addFirst(E e) It is used to insert the given element at the beginning

void addLast(E e) It is used to append the given element to the end of a

void clear() It is used to remove all the elements from a list.

Object clone() It is used to return a shallow copy of an ArrayList.

boolean contains(Object o) It is used to return true if a list contains a specified ele


Iterator<E> descendingIterator() It is used to return an iterator over the elements in a d
order.

E element() It is used to retrieve the first element of a list.

E get(int index) It is used to return the element at the specified positio

E getFirst() It is used to return the first element in a list.

E getLast() It is used to return the last element in a list.

int indexOf(Object o) It is used to return the index in a list of the first occurr or
-1 if the list does not contain any element.

int lastIndexOf(Object o) It is used to return the index in a list of the last occurr or
-1 if the list does not contain any element.

ListIterator<E> listIterator(int index) It is used to return a list-iterator of the elements in pro


specified position in the list.
e
boolean offer(E e) It adds the specified element as the last element of a li

boolean offerFirst(E e) It inserts the specified element at the front of a list.

boolean offerLast(E e) It inserts the specified element at the end of a list.

E peek() It retrieves the first element of a list

E peekFirst() It retrieves the first element of a list or returns null if a

E peekLast() It retrieves the last element of a list or returns null if a

E poll() It retrieves and removes the first element of a list.

E pollFirst() It retrieves and removes the first element of a list, or r

E pollLast() It retrieves and removes the last element of a list, or r

E pop() It pops an element from the stack represented by a list

void push(E e) It pushes an element onto the stack represented by a l

E remove() It is used to retrieve and removes the first element of


E remove(int index) It is used to remove the element at the specified positi

boolean remove(Object o) It is used to remove the first occurrence of the specifie

E removeFirst() It removes and returns the first element from a list.

boolean removeFirstOccurrence(Object o) It is used to remove the first occurrence of the specifie


traversing the list from head to tail).

E removeLast() It removes and returns the last element from a list.

boolean removeLastOccurrence(Object o) It removes the last occurrence of the specified element


list from head to tail).

E set(int index, E element) It replaces the element at the specified position in a lis

Object[] toArray() It is used to return an array containing all the element


s
(from first to the last element).

<T> T[] toArray(T[] a) It returns an array containing all the elements in the pr
the last element); the runtime type of the returned arr
array.

int size() It is used to return the number of elements in a list.

Java LinkedList Example


1.import java.util.*;
2.public class LinkedList1{
3.public static void main(String
args[]){ 4.
5.LinkedList<String> al=new LinkedList<String>();
6.al.add("Ravi");
7.al.add("Vijay");
8.al.add("Ravi");
9.al.add("Ajay");
10.
Iterator<String> itr=al.iterator();
11.
while(itr.hasNext()){
12.
System.out.println(itr.next());
13.
}
14.
15. }
16. }
Output: Ravi
Vijay
Ravi Ajay

Java LinkedList example to add elements


Here, we see different ways to add elements.

1. import java.util.*;
2. public class LinkedList2{
3. public static void main(String args[]){
4. LinkedList<String> ll=new LinkedList<String>();
5. System.out.println("Initial list of elements: "+ll);
6. ll.add("Ravi");
7. ll.add("Vijay");
8. ll.add("Ajay");
9. System.out.println("After invoking add(E e) method: "+ll);
10. //Adding an element at the specific position
11. ll.add(1, "Gaurav");
12. System.out.println("After invoking add(int index, E element) method: "+ll);
13. LinkedList<String> ll2=new LinkedList<String>();
14. ll2.add("Sonoo");
15. ll2.add("Hanumat");
16. //Adding second list elements to the first list
17. ll.addAll(ll2);
18. System.out.println("After invoking addAll(Collection<? extends E> c) method: "+ ll);
LinkedList<String> ll3=new LinkedList<String>(); ll3.add("John");
19.
ll3.add("Rahul");
20.
//Adding second list elements to the first list at specific position ll.addAll(1, ll3);
21.
System.out.println("After invoking addAll(int index, Collection<? extends E> c) method:
22. "+ll);
23.
//Adding an element at the first position
24.
ll.addFirst("Lokesh");
System.out.println("After invoking addFirst(E e) method: "+ll);
25.
//Adding an element at the last position ll.addLast("Harsh");
26.
System.out.println("After invoking addLast(E e) method: "+ll);
27.
28.
29.
30.
31.
32. }
33. }
Initial list of elements: []
After invoking add(E e) method: [Ravi, Vijay, Ajay]
After invoking add(int index, E element) method: [Ravi, Gaurav, Vijay, Ajay]
After invoking addAll(Collection<? extends E> c) method: [Ravi, Gaurav,
Vijay, Ajay, Sonoo, Hanumat]
After invoking addAll(int index, Collection<? extends E> c) method: [Ravi,
John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat]
After invoking addFirst(E e) method:
[Lokesh, Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat] After
invoking addLast(E e) method:
[Lokesh, Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat, Harsh]

Java LinkedList example to remove elements


Here, we see different ways to remove an element.

1.import java.util.*;
2.public class LinkedList3 {
3.
4. public static void main(String [] args)
5. {
6. LinkedList<String> ll=new LinkedList<String>(); ll.add("Ravi");
7. ll.add("Vijay");
8. ll.add("Ajay");
9. ll.add("Anuj");
10. ll.add("Gaurav");
11. ll.add("Harsh");
12. ll.add("Virat");
13. ll.add("Gaurav");
14. ll.add("Harsh");
15. ll.add("Amit");
16. System.out.println("Initial list of elements: "+ll);
17. //Removing specific element from arraylist ll.remove("Vijay");
18. System.out.println("After invoking remove(object) method: "+ll);
19. //Removing element on the basis of specific position ll.remove(0);
20. System.out.println("After invoking remove(index) method: "+ll);
21. LinkedList<String> ll2=new LinkedList<String>(); ll2.add("Ravi");
22. ll2.add("Hanumat");
23. // Adding new elements to arraylist
24. ll.addAll(ll2); System.out.println("Updated list : "+ll);
25. //Removing all the new elements from arraylist ll.removeAll(ll2);
26. System.out.println("After invoking removeAll() method: "+ll);
27. //Removing first element from the list
28.
29.
30.
31.
32.
33.
34. ll.removeFirst();
35. System.out.println("After invoking removeFirst() method: "+ll);
36. //Removing first element from the list ll.removeLast();
37. System.out.println("After invoking removeLast() method: "+ll);
38. //Removing first occurrence of element from the list
39. ll.removeFirstOccurrence("Gaurav");
40. System.out.println("After invoking removeFirstOccurrence() method: "+ll);
41. //Removing last occurrence of element from the list
42. ll.removeLastOccurrence("Harsh");
43. System.out.println("After invoking removeLastOccurrence() method: "+ll);
44.
45.
46. //Removing all the elements available in the list ll.clear();
47. System.out.println("After invoking clear() method: "+ll);
48.
49. }
50. }
Initial list of elements: [Ravi, Vijay, Ajay, Anuj, Gaurav, Harsh, Virat,
Gaurav, Harsh, Amit]
After invoking remove(object) method: [Ravi, Ajay, Anuj, Gaurav, Harsh,
Virat, Gaurav, Harsh, Amit]
After invoking remove(index) method: [Ajay, Anuj, Gaurav, Harsh, Virat,
Gaurav, Harsh, Amit]
Updated list : [Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav, Harsh, Amit, Ravi,
Hanumat]
After invoking removeAll() method: [Ajay, Anuj, Gaurav, Harsh, Virat,
Gaurav, Harsh, Amit]
After invoking removeFirst() method: [Gaurav, Harsh, Virat, Gaurav, Harsh,
Amit]
After invoking removeLast() method: [Gaurav, Harsh, Virat, Gaurav, Harsh]
After invoking removeFirstOccurrence() method: [Harsh, Virat, Gaurav, Harsh]
After invoking removeLastOccurrence() method: [Harsh, Virat, Gaurav]
After invoking clear() method: []

Java LinkedList Example to reverse a list of elements


1.import java.util.*;
2.public class LinkedList4{
3.public static void main(String args[]){ 4.
5.
6.LinkedList<String> ll=new LinkedList<String>();
7. ll.add("Ravi");
8.ll.add("Vijay");
9.ll.add("Ajay");
//Traversing the list of elements in reverse order
10.
11. Iterator i=ll.descendingIterator();
12.
while(i.hasNext())
{
13. System.out.println(i.next());
14. }
15.
16. }
17. }
Output: Ajay Vijay
Ravi

Java LinkedList Example: Book


1.import java.util.*;
2.class Book {
3.int id;
4.String name,author,publisher;
5.int quantity;
6.public Book(int id, String name, String author, String publisher, int quantity) {
7.this.id = id;
8.this.name = name;
9.this.author = author;
10.this.publisher = publisher;
11.this.quantity = quantity;
12. }
13. }
14.public class LinkedListExample {
15.public static void main(String[] args) {
16.//Creating list of Books
17.List<Book> list=new LinkedList<Book>();
18.//Creating Books
19.Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
20.Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw
Hill",4);
21.Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
22.//Adding Books to list
23.list.add(b1);
24.list.add(b2);
25.list.add(b3);
26.//Traversing list
27.for(Book b:list){
28.System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);

29. }
30. }
31. }
Output:

101 Let us C Yashwant Kanetkar BPB 8


102 Data Communications & Networking Forouzan Mc Graw Hill 4
103 Operating System Galvin Wiley 6
Introduction to JDBC
JDBC

JDBC (Java Database Connectivity) API allows Java programs to connect to


databases

Database access is the same for all database vendors

The JVM uses a JDBC driver to translate generalized JDBC calls into vendor
specific database calls

There are four general types of JDBC drivers


We will look at Type 4 …
Pure Java Driver (Type 4)

These drivers convert the JDBC API calls to direct network calls using vendor-
specific networking protocols by making direct socket connections with the
database
It is the most efficient method to access database, both in performance and
development time
It is the simplest to deploy
All major database vendors provide pure Java JDBC drivers for their databases
and they are also available from third party vendors
For a list of JDBC drivers, refer to
http://industry.java.sun.com/products/jdbc/drivers
Pure Java Driver (2)

DB Client Server
Java
Application
Data Source

JDBC
JDBC Driver
API
Typical JDBC Programming Procedure

1. Load the database driver


2. Obtain a connection
3. Create and execute statements (SQL queries)
4. Use result sets (tables) to navigate through the results
5. Close the connection
Driver Manager

The purpose of the java.sql.DriverManger class in JDBC is to provide a


common access layer on top of different database drivers used in an
application

DriverManager requires that each driver required by the application


must be registered before use, so that the DriverManager is aware of it

Load the database driver using ClassLoader :


Class.forName (“oracle.jdbc.driver.OracleDriver”);
Connecting to a Database

Type 4 JDBC Driver – Oracle Server

Class.forName (“oracle.jdbc.driver.OracleDriver”);
con = DriverManager.getConnection (
“jdbc:oracle:thin:@bonsai.ite.gmu.edu:1521:ite”,
“accountname", “password”);

Type 4 JDBC Driver – MySQL Server

Class.forName (“org.gjt.mm.mysql.Driver”);
con = DriverManager.getConnection
(“jdbc:mysql://localhost/databasename”, uid, passwd);
Creating Tables

Creating a Coffee table


CREATE TABLE COFFEES (COF_NAME VARCHAR(32),
SUP_ID INTEGER, PRICE FLOAT, SALES INTEGER,
TOTAL INTEGER)

SQL query
• Creating JDBC statements
Statement stmt = con.createStatement ();
• Execute a statement
stmt.executeUpdate (“CREATE TABLE COFFEES “ +
“(COF_NAME VARCHAR(32), SUP_ID INTEGER,
PRICE FLOAT, “ + “SALES INTEGER, TOTAL
INTEGER)”);
Execute Statements

This uses executeUpdate because the SQL statement contained in


createTableCoffees is a DDL (data definition language) statement

Statements that create a table, alter a table, or drop a table are all
examples of DDL statements and are executed with the method
executeUpdate

executeUpdate is also used to execute SQL statements that update a


table
Execute Statements

In practice, executeUpdate is used far more often to update tables


than it is to create them because a table is created once but may be
updated many times

The method used most often for executing SQL statements is


executeQuery

executeQuery is used to execute SELECT statements, which


comprise the vast majority of SQL statements
Entering Data into a Table

Statement stmt = con.createStatement();


stmt.executeUpdate ( "INSERT INTO COFFEES " + "VALUES
('Colombian', 101, 7.99, 0, 0)");
stmt.executeUpdate ( "INSERT INTO COFFEES " + "VALUES
('French_Roast', 49, 8.99, 0, 0)" );
stmt.executeUpdate ( "INSERT INTO COFFEES " + "VALUES
('Espresso', 150, 9.99, 0, 0)" );
stmt.executeUpdate ( "INSERT INTO COFFEES " + "VALUES
('Colombian_Decaf', 101, 8.99, 0, 0)" );
stmt.executeUpdate ( "INSERT INTO COFFEES " + "VALUES
('French_Roast_Decaf', 49, 9.99, 0, 0)" );
Getting Data From a Table

ResultSet rs = stmt.executeQuery ("SELECT COF_NAME,


PRICE FROM COFFEES");
while (rs.next())
{
String s = rs.getString ("COF_NAME");
float n = rs.getFloat ("PRICE");
System.out.println (s + " " + n);
}
JDBC Data Source Architecture

Application JDBC Database

JNDI

Connection Manager

You might also like