0% found this document useful (0 votes)
3 views101 pages

Java Multithreading Overview and Concepts

The document provides an overview of multithreading in Java, detailing its features, thread life cycle, and methods for creating and managing threads. It explains thread priorities, synchronization, and inter-thread communication, along with examples of input and output operations using Java's io package. Additionally, it covers the creation of threads using both the Thread class and Runnable interface, as well as methods for reading and writing data.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views101 pages

Java Multithreading Overview and Concepts

The document provides an overview of multithreading in Java, detailing its features, thread life cycle, and methods for creating and managing threads. It explains thread priorities, synchronization, and inter-thread communication, along with examples of input and output operations using Java's io package. Additionally, it covers the creation of threads using both the Thread class and Runnable interface, as well as methods for reading and writing data.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

RAGHU

ENGINEERING COLLEGE
(AUTONOMOUS | VISAKHAPATNAM)

Unit-IV
Multithreading , Random File Access,
Collections
Java Programming RAGHU ENGINEERING COLLEG 1
Introduction to Multithreading
• Multithreading is a Java feature that allows concurrent
execution of two or more parts of a program for maximum
utilization of CPU. Each part of such program is called a
thread.

Execution of tasks can be done in two ways. They are:


• Single tasking
• Multitasking

In single tasking only one task executed at a time. But, in


multi-tasking more than one task can be run
simultaneously.
Java Programming RAGHU ENGINEERING COLLEG 2
Introduction to Multithreading

Multitasking can be of two types. They are:

Process based multitasking: It allows the computer to run


two or more programs concurrently.

Thread based multitasking: It allows the computer to run


two or more parts of a single program simultaneously.

Java Programming RAGHU ENGINEERING COLLEG 3


Thread

•Thread can be defined as set of executable instructions that


are executed independently.
•Thread is the smallest unit of dispatchable code.
•Thread is a light-weight process, because they utilize
minimum resources of the system.

Uses of threads:
• Threads are mainly used in server-side programs to serve
the needs of multiple clients on a network
• Threads are used to create games and animations

Java Programming RAGHU ENGINEERING COLLEG 4


Thread life cycle

Thread life cycle defines the states which are to be visited by


the thread during it’s life time.

The following are the life cycle states of a thread:


Born state
Runnable state
Running state
Waiting/Suspend state
Dead state

Java Programming RAGHU ENGINEERING COLLEG 5


Thread life cycle

1. Born state:
When a thread object is created it is said to be a new
thread is created. And it said to be entered into a state called
Born state.

2. Runnable state:
After a thread is created, it is waiting to be processed.
To process the thread it requires the processor. When start()
method is executed on the thread, then it enters into a
runnable state in which thread is in queue for the execution.

Java Programming RAGHU ENGINEERING COLLEG 6


Thread life cycle
3. Running state:
When the thread gets the chance of processing, then it
starts it’s execution by invoking a method called run(). This
state is called Running state.

4. Waiting/Suspend state:
The thread can be suspended for a specific amount of
time by invoking methods like wait(), sleep(), suspend(). The
state in which the thread is blocked is called Suspend state.

5. Dead state:
When the thread execution is completed, then it is said
to enter into a state called Dead state.
Java Programming RAGHU ENGINEERING COLLEG 7
Thread life cycle

Java Programming RAGHU ENGINEERING COLLEG 8


[Link]

Java Programming RAGHU ENGINEERING COLLEG 9


[Link]
Constructor Action Performed
Thread() Allocates a new Thread object.

Thread(Runnable target) Allocates a new Thread object.

Thread(Runnable target, String name) Allocates a new Thread object.

Thread(String name) Allocates a new Thread object.

Thread(ThreadGroup group, Runnable target) Allocates a new Thread object.

Allocates a new Thread object so that it has


Thread(ThreadGroup group, Runnable target, targeted as its run object, has the specified name as
String name) its name, and belongs to the thread group referred
to by a group.

Allocates a new Thread object so that it has


Thread(ThreadGroup group, Runnable target, targeted as its run object, has the specified name as
String name, long stackSize) its name, and belongs to the thread group referred
to by group, and has the specified stack size.

Thread(ThreadGroup group, String name) Allocates a new Thread object

Java Programming RAGHU ENGINEERING COLLEG 10


Creation of Thread

When a Java program starts up, one thread begins


immediately. This is usually called ‘Main thread’ of your
program, because it is the one that takes the responsibility to
execute the Java program.

The main thread is important because:


• It is the thread useful to create child threads.
• It is the last thread to finish because it performs various
shutdown actions
• It is the thread which is created automatically when your
program started.
Java Programming RAGHU ENGINEERING COLLEG 11
Creation of Thread
Java program to know the status of current main thread:
class Current
{
public static void main(String args[])
{
Thread t=[Link]();
[Link](“Current thread:”+t);
[Link](“name:”+[Link]());
}
}
Output:
Current thread: Thread[main,5,main]
name: main
Java Programming RAGHU ENGINEERING COLLEG 12
Creation of Thread
In the previous program currentThread() is a static
method of Thread class. So we called it as
[Link](). This method gave the object of
currently running thread.

The output is, Thread[main,5,main]. In this ‘Thread’


indicates current thread is an object of Thread class. And first
‘main’ is the name, 5 is the priority and second ‘main’ is the
thread group name to which thread belongs.

Java Programming RAGHU ENGINEERING COLLEG 13


Creation of Thread
A thread can be created by instantiating an object of type
Thread. Basically, thread can be created in two ways:
• By extending the Thread class
• By implementing Runnable interface.
Steps to create a thread:
Step1: Import the [Link].*; package
Step2: Create a user defined thread class by extending the
Thread class or by implementing the Runnable interface as
below:
class <class_name> extends Thread
Or
class <class_name> implements Runnable
Java Programming RAGHU ENGINEERING COLLEG 14
Creation of Thread
Step 3: Implementing a constructor for the user defined thread
class
<thread_class_name>()
{
..body of the constructor
}
Step 4: Implement the run method which contains the statements
required to perform the desired task
public void run()
{
//statements
}
Step 5: Create an object for newly created thread class and pass it
as parameter for the thread class constructor if required.
Java Programming RAGHU ENGINEERING COLLEG 15
Creation of Thread

program to create a thread by using the Thread class

Program to create a thread by using the Runnable interface

Note: In multi-threaded environment the main thread will be


executed first then child thread will start its execution.

Java Programming RAGHU ENGINEERING COLLEG 16


Multiple Threads
We can also create multiple threads in single program.
To make this possible we have to invoke the Thread class
constructor for as many times we want to create the thread.

It means that if we want to create three threads then we


have to call Thread class constructor for three times.

program to create multiple threads

Java Programming RAGHU ENGINEERING COLLEG 17


isAlive() and join() methods
The method isAlive() is useful to determine whether a
thread has finished. This method is defined by Thread class. The
general form of this method is as below:
final boolean isAlive();
The isAlive() method returns true if the thread upon which
it is called is still active otherwise it returns false.
The method join() allows one thread to wait until
another thread completes its execution. The general form of
this method is as below:
final void join() throws InterruptedException
If t is a Thread object whose thread is currently
executing, then [Link]() will make sure that t is terminated
before the next instruction is executed by the program.
program to demonstrateRAGHU
Java Programming
isAlive() and join() methods
ENGINEERING COLLEG 18
Thread priorities
• Thread priorities are used by the scheduler to decide when
each thread should be allowed to run.

• Higher-priority threads get more CPU time than lower-


priority threads.

• The threads with equal priority will get equal access time.

• To set a thread’s priority, we can use the method


setPriority(), which is a member of the Thread class. The
general form is:
final void setPriority(int level)
Java Programming RAGHU ENGINEERING COLLEG 19
Thread priorities
• Here, level specifies the new priority setting for the calling
thread.

• The value of level must be within the range


MIN_PRIORITY and MAX_PRIORITY. Currently these
values are 1 and 10 respectively. To return a thread to default
priority, specify NORM_PRIORITY, which is 5.

• We can obtain the current thread priority by using


getPriority() method.

Java Programming RAGHU ENGINEERING COLLEG 20


Thread priorities: program
class TPriority extends Thread
{
Thread t;
TPriority()
{
t=new Thread(this);
[Link](Thread.MAX_PRIORITY);
[Link]("Thread priority:"+[Link]());

}
Output:
public static void main(String args[])
{ Thread priority:10
new TPriority();
}
} Java Programming RAGHU ENGINEERING COLLEG 21
Thread synchronization
Synchronization can be defined as a process of
enabling single thread to access shared resource. When two
or more threads need access to a shared resource, they need
some way to ensure that the resource will be used by only
one thread at a time. Otherwise it leads to conflict in the
resource. The process by which this is achieved is called
‘Synchronization’.

Key to synchronization is the concept of the monitor. A


monitor is an object that is used as a mutually exclusive lock.
Only one thread can own a monitor at a given time. When a
thread acquires a lock, it is said to have entered the monitor.
Java Programming RAGHU ENGINEERING COLLEG 22
Thread synchronization

All other threads attempting to enter the monitor will


be suspended until the first thread exits the monitor. These
other threads are said to be waiting for the monitor. A thread
that owns a monitor can re-enter the same monitor if it
desires.

We can synchronize the code by using two ways:


• Using synchronized method
• Using synchronized statement

Java Programming RAGHU ENGINEERING COLLEG 23


Thread synchronization

Using synchronized method:


• Synchronized method is a method which is having the
keyword ‘synchronized’.
• While one thread access the synchronized method, all other
threads must wait until it release the locked thread.

program to demonstrate synchronized method

Java Programming RAGHU ENGINEERING COLLEG 24


Thread synchronization
Using synchronized statement:
In this way, simply put calls to methods which need to
be synchronized inside a synchronized block.
The general form of this as below:
synchronized(object)
{
//calling statements to a method
}
Here, object is a reference to the object being
synchronized. The following is the modified version of the
previous program using synchronized block.
program to demonstrate synchronized block
Java Programming RAGHU ENGINEERING COLLEG 25
suspend() and resume() methods
Prior to Java2, a program uses suspend() and resume()
methods which are defined by Thread class, to pause and
restart the execution of the thread. These two methods are
deprecated in the later versions of Java. The general forms of
this method are as below:

final void suspend() – this method is used to pause the thread

final void resume() – this method is used to restart the thread


which is in paused state.

program to demonstrate suspend() and resume() methods


Java Programming RAGHU ENGINEERING COLLEG 26
Communication between Threads

Inter-thread communication is all about allowing


synchronized threads to communicate with each other.

Inter-thread communication is a mechanism in which a


thread is paused while running in its critical section and
another thread to be executed is allowed to enter (or lock) in
the same critical section.

Java Programming RAGHU ENGINEERING COLLEG 27


Communication between Threads

wait() – tells the calling thread to give up the lock over a


resource and go to sleep until some other thread calls
notify().

notify() – this method wakes up a thread that called wait() on


the same object.

notifyAll() – this method wakes up all the threads which are


called wait() on the same object.

program to demonstrate Inter Thread Communication


Java Programming RAGHU ENGINEERING COLLEG 28
Input Output Introduction

Input and Output:


Input represents data given to a program and output
represents data displayed as a result of a program.

Stream:
A stream represents flow of data from one place to
another place. A stream can carry data from keyboard to
program or from memory to printer or to a file or to a output
device. A stream is always required to move data from one
place to another.

Java Programming RAGHU ENGINEERING COLLEG 29


Input Output: io package
[Link].* package:
All stream classes are present in [Link].* package.
This package contains a lot of classes, all of which can be
classified as two categories, as Byte streams and
Character/Text streams.

Byte streams represent data in the form of individual


bytes. Text streams represent data as Unicode characters. If a
class ends with ‘Stream’ then it comes under byte streams. If
a class ends with ‘Reader’ or ‘Writer’ then it is comes under
character streams.

Java Programming RAGHU ENGINEERING COLLEG 30


Important classes of [Link].* package
Byte stream classes:
DataInputStream – It contains the methods for reading the data.

FileInputStream – Input stream that reads data from a file.

BufferedInputStream – Buffered input stream to read data by


improving efficiency.

DataOutputStream – It contains methods for writing the data.

FileOutputStream – Output stream that writes data to a file.

BufferedOutputStream – Buffered output stream to write data by


improving efficiency.
Java Programming RAGHU ENGINEERING COLLEG 31
Important classes of [Link].* package
Character/Text stream classes:
InputStreamReader – Input stream that translates bytes to
character.

FileReader – Input stream that reads from a file.

BufferedReader – Buffered input character stream.

OutputStreamWriter – Output stream that translates characters to


bytes.

FileWriter – Output stream that writes to a file.

BufferedWriter – Buffered output character stream.


Java Programming RAGHU ENGINEERING COLLEG .32
Steps to read and write data
Step1: Connect source to input byte stream or character
stream class object.

Step2: Read the data and store it in memory using read() or


readLine() method.

Step3: Connect the destination with anyone output byte


stream or character stream class object.

Step4: Write the data to the destination using write() method.


Note:All the methods of these stream classes are raising
IOException. So, we need to throws the exception out of the
programs.
Java Programming RAGHU ENGINEERING COLLEG .33
Program to read data from keyboard and
display
import [Link].*;
class IODemo1
{
public static void main(String args[])throws IOException
{
DataInputStream dis=new DataInputStream([Link]);
char ch;
while((ch=(char)[Link]())!='@')
{
[Link](ch);
} Output:
} Hello Welcome to IO Operations
} Hello Welcome to IO Operations
Java Programming RAGHU ENGINEERING COLLEG 34
Program to read data from file and display
import [Link].*;
class IODemo2
{
public static void main(String args[])throws IOException
{
FileInputStream fis=new
FileInputStream("[Link]");
int ch;
while((ch=[Link]())!=-1)
{
[Link]((char)ch);
}
}
} //Javathis program displaysRAGHU
Programming the contents
ENGINEERING COLLEG of file [Link] 35
Program to read data from keyboard into file
import [Link].*;
class FileWrite1
{
public static void main(String args[])throws IOException
{
DataInputStream dis=new DataInputStream([Link]);
FileOutputStream fos=new FileOutputStream("[Link]");
char ch;
while((ch=(char)([Link]()))!='@')
{
[Link](ch);
}
} // this program writes all the contents entered by user into file
} // ends reading data from keyboard when user enters @.
Java Programming RAGHU ENGINEERING COLLEG 36
Program to write data from one file to another
import [Link].*;
class FileWrite2
{
public static void main(String args[])throws IOException
{
FileInputStream fis=new FileInputStream("[Link]");
FileOutputStream fos=new FileOutputStream("[Link]");
int ch;
while((ch=[Link]())!=-1)
{
[Link]((char)ch);
}
}
} //this program copies data from [Link] to [Link]
Java Programming RAGHU ENGINEERING COLLEG 37
Buffered IO Operation

Improving the efficiency of reading and writing using


Buffered Streams:

While reading the data, if we use buffered classes they


provide a buffer (temporary block of memory) which is
first filled with characters and then all the characters from
the buffer can be written to the destination at once. By
using these classes the time taken to read or write the data
gradually reduced.

Java Programming RAGHU ENGINEERING COLLEG 38


Buffered IO Operation
The buffered classes can be used as below:
To read:
BufferedInputStream bis=new
BufferedInputStream(source_reference,size);
Here, size represents the capacity of the buffer in terms of
bytes. By default it is 512 bytes.
To write:
BufferedOuputStream bos=new
BufferedOuputStream(destination_reference,size);

program to read data from keyboard and write it into a file


using
Java buffered class RAGHU ENGINEERING COLLEG
Programming 39
RandomAccessFile
• Random access file is a special kind of file in Java which
allows non-sequential or random access to any location in
file. This means you don't need to start from 1st line if you
want to read line number 10

• A random access file behaves like a large array of bytes.


There is a cursor implied to the array called file pointer, by
moving the cursor we do the read write operations.

• If end-of-file is reached before the desired number of bytes


has been read then EOFException is thrown. It is a type of
IOException.

Java Programming RAGHU ENGINEERING COLLEG 40


RandomAccessFile: Constructors
RandomAccessFile(File file, String mode)
Creates a random access file stream to read from, and
optionally to write to, the file specified by the File
argument.
RandomAccessFile(String name, String mode)
Creates a random access file stream to read from, and
optionally to write to, a file with the specified name.

program to demonstrate RandomAccessFile

Java Programming RAGHU ENGINEERING COLLEG 41


Collections in java
• A Collection is a group of individual objects represented as
a single unit.

• Java provides Collection Framework which defines several


classes and interfaces to represent a group of objects as a
single unit.

Need for Collection framework:


Before Collection Framework (or before JDK 1.2) was
introduced, the standard methods for grouping Java objects
(or collections) were Arrays or Vectors or Hashtables. All of
these collections had no common interface.
Java Programming RAGHU ENGINEERING COLLEG 42
Hierarchy of Collection framework

Java Programming RAGHU ENGINEERING COLLEG 43


List Interface

• The [Link] is a child interface of Collection.

• It is an ordered collection of objects in which duplicate


values can be stored.

• Since List preserves the insertion order, it allows positional


access and insertion of elements.

• List interface is implemented by ArrayList, LinkedList,


Vector and Stack classes.

Java Programming RAGHU ENGINEERING COLLEG 44


List Interface
Creating List Objects:
List is an interface, and the instances of List can be created
as:
List<type> obj = new List<type>();
type is the type of object to be stored in List.
For ArrayList,
ArrayList<type> obj = new ArrayList<type>();
Operations on List:
List Interface extends Collection, hence it supports all the
operations of Collection Interface, along with following
additional operations:
1. Positional access 2. Search
3. Iteration 4. Range-view
Java Programming RAGHU ENGINEERING COLLEG 45
List Interface: Positional access
List allows add, remove, get and set operations based on
numerical positions of elements in List.

add() method:
void add(int index,Object O): This method adds given
element at specified index.

Example Snippet:
ArrayList<Integer> l1 = new ArrayList<Integer>();
[Link](0, 10); // adds 10 at index 0
[Link](1, 20); // adds 20 at index 1
[Link](l1); // [10, 20]
Java Programming RAGHU ENGINEERING COLLEG 46
List Interface: Positional access
addAll() method:

boolean addAll(int index, Collection c): This method adds


all elements from specified collection to list.

First element gets inserted at given index. If there is


already an element at that position, that element and other
subsequent elements(if any) are shifted to the right by
increasing their index.

Java Programming RAGHU ENGINEERING COLLEG 47


List Interface: Positional access
Example Snippet:
ArrayList<Integer> l1 = new ArrayList<Integer>();
[Link](0,10);
[Link](1,20);
ArrayList<Integer> l2 = new ArrayList<Integer>();
[Link](0,30);
[Link](1,40);
[Link](1,l2);
Output:
[Link](l1);
[10, 30, 40, 20]

Java Programming RAGHU ENGINEERING COLLEG 48


List Interface: Positional access
remove() method:

Object remove(int index): This method removes an element


from the specified index. It shifts subsequent elements(if any)
to left and decreases their indices by 1.

Example Snippet:
//consider l1 contains [10, 20, 30, 40]
[Link](2);
[Link](l1);

Output: [10, 20, 40]


Java Programming RAGHU ENGINEERING COLLEG 49
List Interface: Positional access
get() method:

Object get(int index): This method returns element at the


specified index.

Example: [Link](2) // returns element from l1 at index 2.

set() method:

Object set(int index, Object new): This method replaces


element at given index with new element. This function
returns the element which was just replaced by new
element.
Java Programming RAGHU ENGINEERING COLLEG 50
List Interface: Positional access
Example Snippet for get() and set() methods:
ArrayList<Integer> l1 = new ArrayList<Integer>();
[Link](0,10);
[Link](1,20);
[Link](2,30);
[Link](3,40);
int x = [Link](2); Output:
[Link](x); 30
int r = [Link](1,50); 20
[Link](r); [10, 50, 30, 40]
[Link](l1);

Java Programming RAGHU ENGINEERING COLLEG 51


List Interface: Search

List provides methods to search element and returns its


numeric position. Following two methods are supported by
List for this operation:

int indexOf(Object o): This method returns first occurrence


of given element or -1 if element is not present in list.

int lastIndexOf(Object o): This method returns the last


occurrence of given element or -1 if element is not present in
list.

Java Programming RAGHU ENGINEERING COLLEG 52


List Interface: Search
Example Snippet:
ArrayList<String> s = new ArrayList<String>();
[Link]("C");
[Link]("CPP"); Output:
2
[Link]("Python");
4
[Link]("Java");
[Link]("Python");
[Link]([Link]("Python"));
[Link]([Link]("Python"));

Java Programming RAGHU ENGINEERING COLLEG 53


List Interface: Iterator
ListIterator Interface is used to traverse the elements in
backward and forward directions. Some important methods
of java ListIterator are:
Syntax for creating ListIterator:
ListIterator <type> obj= list_obj.listIterator();

boolean hasNext() This method returns true if the list


iterator has more elements while traversing the list in the
forward direction.

next() This method returns the next element in the list


and advances the cursor position.
Java Programming RAGHU ENGINEERING COLLEG 54
List Interface: Iterator
int nextIndex() This method returns the index of the
element that would be returned by a subsequent call to next()

boolean hasPrevious() This method returns true if this list


iterator has more elements while traversing the list in the
reverse direction.

int previousIndex() This method returns the index of


the element that would be returned by a subsequent call to
previous().

previous() This method returns the previous element in the


list and moves the cursor position backward.
Java Programming RAGHU ENGINEERING COLLEG 55
List Interface: Iterator
Example Snippet:
ArrayList<String> s = new ArrayList<String>();
[Link]("C");
[Link]("CPP");
[Link]("Python"); Output:
C
[Link]("Java");
CPP
ListIterator<String> li=[Link](); Python
while([Link]()) Java
[Link]([Link]()); 4
[Link]([Link]());
Example Program on ListIterator
Java Programming RAGHU ENGINEERING COLLEG 56
List Interface: Range - view

List Interface provides a method to get the List view of the


portion of given List between two indices. Following is the
method supported by List for range view operation.

List subList(int fromIndex,int toIndex)


This method returns List view of specified List between
fromIndex(inclusive) and toIndex(exclusive).

Java Programming RAGHU ENGINEERING COLLEG 57


List Interface: Range - view
Example Snippet:
List<Integer> l1 = new ArrayList<Integer>();
List<Integer> l2 = new ArrayList<Integer>();
[Link](10); [Link](20);
[Link](30); [Link](40);
[Link](50); [Link](60); Output:
[Link](70); [Link](80); [30, 40, 50, 60, 70]
l2 = [Link](2,7);
[Link](l2);

Java Programming RAGHU ENGINEERING COLLEG 58


LinkedList
•Linked List are linear data structures where the elements are
not stored in contiguous locations and every element is a
separate object with a data part and address part.

•The elements are linked using pointers and addresses. Each


element is known as a node. Due to the dynamicity and ease
of insertions and deletions, they are preferred over the
arrays.

•To store the elements in a linked list we use a doubly linked


list which provides a linear data structure.

Java Programming RAGHU ENGINEERING COLLEG 59


LinkedList
In Java, LinkedList class implements the list interface. The
LinkedList class also consists of various constructors and
methods like other java collections.

Constructors for LinkedList:


• LinkedList(): Used to create an empty linked list.
• LinkedList(Collection C): Used to create a ordered list
which contains all the elements of a specified collection, as
returned by the collection’s iterator.

Syntax for creating LinkedList:


LinkedList<type> obj = new LinkedList<type>();
Example program on LinkedList
Java Programming RAGHU ENGINEERING COLLEG 60
LinkedList
Some important methods for Java LinkedList:

add​(int index, E element) This method Inserts the specified


element at the specified position in this list.
Usage: [Link](2,15); //l1 is a Linked List

add​(element) This method Appends the specified element to


the end of this list.

addAll​(int index, Collection c): This method inserts all of


the elements in the specified collection into this list, starting
at the specified position.
Usage: [Link](1,l2); //l2 can be an ArrayList also.
Java Programming RAGHU ENGINEERING COLLEG 61
LinkedList
addAll​(Collection c) This method appends all of the
elements in the specified collection to the end of this list, in
the order that they are returned by the specified collection’s
iterator.

addFirst​(element) This method inserts the specified element


at the beginning of this list.
Usage: [Link](103);

addLast​(Element element) This method Appends the


specified element to the end of this list.

Java Programming RAGHU ENGINEERING COLLEG 62


LinkedList
clear​() This method removes all of the elements from this
list.
Usage: [Link]();

clone​() This method returns a shallow copy of this


LinkedList.
Usage: l2=(LinkedList)[Link]();

contains​(element) This method returns true if this list


contains the specified element, otherwise false.
Usage: [Link](130);

Java Programming RAGHU ENGINEERING COLLEG 63


LinkedList

get​(int index) This method returns the element at the


specified position in this list.
Usage: [Link](2); // 2 is index.

getFirst​() This method returns the first element in this list.


Usage: [Link]()

getLast​() This method returns the last element in this list.

remove​() This method retrieves and removes the head (first


element) of this list.
Java Programming RAGHU ENGINEERING COLLEG 64
LinkedList
remove​(int index) This method removes the element at the
specified position in this list.

Try these methods:


• removeFirst​()
• removeFirstOccurrence​(Object o):
• removeLast​():
• removeLastOccurrence​(Object o):
• size​():
• indexOf​(Object o):
• lastIndexOf​(Object o):

Java Programming RAGHU ENGINEERING COLLEG 65


ArrayList vs LinkedList

ArrayList internally uses LinkedList internally uses


a dynamic array to store the a doubly linked list to store
elements. the elements.

Manipulation with ArrayList Manipulation with LinkedList


is slow because it internally is faster than ArrayList
uses an array. If any element because it uses a doubly linked
is removed from the array, all list, so no bit shifting is
the bits are shifted in required in memory.
memory.

Java Programming RAGHU ENGINEERING COLLEG 66


ArrayList vs LinkedList

An ArrayList class can act as LinkedList class can act as a list


a list only because it and queue both because it
implements List only. implements List and Deque
interfaces.

ArrayList is better for storing LinkedList is better for


and accessing data. manipulating data.

Java Programming RAGHU ENGINEERING COLLEG 67


Sets: HashSet
•A Set is a Collection that cannot contain duplicate elements.
It models the mathematical set abstraction.

•The Set interface contains only methods inherited from


Collection and adds the restriction that duplicate elements are
prohibited.

Types of Sets in java are:


HashSet TreeSet LinkedHashSet
HashSet:
Java HashSet class is used to create a collection that uses a
hash table for storage. It inherits the AbstractSet class and
implements Set interface.
Java Programming RAGHU ENGINEERING COLLEG 68
HashSet
•HashSet stores the elements by using a mechanism
called hashing.

•HashSet contains unique elements only, allows null value.

•HashSet doesn't maintain the insertion order. Here, elements


are inserted on the basis of their hash code.

•HashSet is the best approach for search operations.

•The initial default capacity of HashSet is 16, and the load


factor is 0.75.
Java Programming RAGHU ENGINEERING COLLEG 69
HashSet
Initial Capacity: The initial capacity means the number of
buckets when hashtable (HashSet internally uses hashtable
data structure) is created. The number of buckets will be
automatically increased if the current size gets full.

Load Factor: The load factor is a measure of how much the


HashSet is allowed to get filled before its capacity is
automatically increased. When the number of entries in the
hash table exceeds the product of the load factor and the
current capacity, the hash table is rehashed (that is, internal
data structures are rebuilt) so that the hash table has
approximately twice the number of buckets.
Java Programming RAGHU ENGINEERING COLLEG 70
HashSet
Constructors in HashSet

HashSet h = new HashSet();


Default initial capacity is 16 and default load factor is 0.75.

HashSet h = new HashSet(int initialCapacity);


default loadFactor of 0.75

HashSet h = new HashSet(int initialCapacity, float


loadFactor);

HashSet h = new HashSet(Collection C);


Java Programming RAGHU ENGINEERING COLLEG 71
HashSet
Example Snippet:
HashSet<String> set=new HashSet(s);
[Link]("One"); Output:
[Link]("Two"); Five
[Link]("Three"); One
[Link]("Four"); Four
[Link]("Five");
Two
Iterator<String> i=[Link]();
while([Link]()) Three
[Link]([Link]());

Program to create HashSet from existing Collection


Java Programming RAGHU ENGINEERING COLLEG 72
HashSet

Methods of java HashSet class are:


• add()
• clear()
• clone()
• contains()
• isEmpty()
• iterator()
• remove()
• size()

Java Programming RAGHU ENGINEERING COLLEG 73


TreeSet

•Java TreeSet class implements the Set interface that uses a


tree for storage.

• It inherits AbstractSet class and implements the


NavigableSet interface. The objects of the TreeSet class are
stored in ascending order.

• Java TreeSet class contains unique elements only like


HashSet.

• Java TreeSet class access and retrieval times are quiet fast.

Java Programming RAGHU ENGINEERING COLLEG 74


TreeSet
•Java TreeSet class doesn't allow null element.

•Java TreeSet class is non synchronized.

•Java TreeSet class maintains ascending order.


Constructors of TreeSet class
TreeSet t = new TreeSet(); This will create empty TreeSet
object in which elements will get stored in default natural
sorting order.

TreeSet t = new TreeSet(Collection col); This constructor


is used when any conversion is needed from any Collection
object to TreeSet object.
Java Programming RAGHU ENGINEERING COLLEG 75
TreeSet
Example Snippet:
TreeSet<Integer> set=new TreeSet();
[Link](99); Output:

[Link](34); 34
[Link](79); 50
[Link](61); 61
[Link](50); 79
Iterator<Integer> i=[Link](); 99
while([Link]())
[Link]([Link]());

Java Programming RAGHU ENGINEERING COLLEG 76


TreeSet
All the methods of HashSet can be used on TreeSet and
additionally the following methods can be used:

higher(element) It returns the closest greatest element of the


specified element , or null there is no such element.

lower(element) It returns the closest least element of the


specified element, or null there is no such element.

ceiling(element)
It returns the equal or closest greatest element of the specified
element, or null there is no such element.
Java Programming RAGHU ENGINEERING COLLEG 77
TreeSet
floor(element)
It returns the equal or closest least element of the specified
element, or null there is no such element.

first()
It returns the first (lowest) element currently in this sorted
set.

last()
It returns the last (highest) element currently in this sorted
set.

program to demonstrate TreeSet methods


Java Programming RAGHU ENGINEERING COLLEG 78
LinkedHashSet
• Java LinkedHashSet class is a Hashtable and Linked list
implementation of the Set interface. It inherits HashSet class
and implements Set interface.

• Java LinkedHashSet class contains unique elements only


like HashSet.

• Java LinkedHashSet class provides all optional set


operation and permits null elements.

• Java LinkedHashSet class is non synchronized.

• Java LinkedHashSet class maintains insertion order.


Java Programming RAGHU ENGINEERING COLLEG 79
LinkedHashSet
Constructors
LinkedHashSet(): to create a default HashSet.

LinkedHashSet(Collection C): Used in initializing the HashSet with


the elements of the collection C

LinkedHashSet(int capacity): Used to initialize the size of the


LinkedHashSet with the integer mentioned in the parameter.

LinkedHashSet(int capacity, float fillRatio): Can be used to initialize


both the capacity and the fill ratio, also called the load capacity of the
LinkedHashSet with the arguments mentioned in the parameter. When
the number of elements exceeds the capacity of the hash set is
multiplied with the fill ratio thus expanding the capacity of the
LinkedHashSet
Java Programming RAGHU ENGINEERING COLLEG 80
LinkedHashSet
Example Snippet:
LinkedHashSet<Integer> set=new LinkedHashSet();
[Link](99);
[Link](34); Output:
[Link](79); 99
[Link](61); 34
[Link](50); 79
Iterator<Integer> i=[Link](); 61
while([Link]()) 50
[Link]([Link]());

Java Programming RAGHU ENGINEERING COLLEG 81


LinkedHashSet
LinkedHashSet supports following methods:
• add(Element e)
• clear()
• clone()
• contains(Element e)
• isEmpty()
• iterator()
• remove(Element e)
• size()
• addAll(Collection c)
• removeAll(Collection c)

program to demonstrate addAll() and removeAll() methods


Java Programming RAGHU ENGINEERING COLLEG 82
Queue
• The Queue interface is available in [Link] package and
extends the Collection interface.

• The Queue collection is used to hold the elements about to


be processed and provides various operations like the
insertion, removal etc.

• It is an ordered list of objects with its use limited to insert


elements at the end of the list and deleting elements from the
start of list i.e. it follows the FIFO or the First-In-First-Out
principle.

Java Programming RAGHU ENGINEERING COLLEG 83


Queue
• Being an interface the Queue needs a concrete class for the
declaration and the most common classes are the LinkedList
and PriorityQueue in Java.

Syntax for creating a queue:


Queue<Type> obj = new LinkedList<>();

or

Queue<Type> obj = new PriorityQueue<>();

Java Programming RAGHU ENGINEERING COLLEG 84


Queue
The Java Queue supports all methods of Collection interface
including insertion, deletion etc.

Some of the important methods are:


add() size()
peek()- This method is used to view the head of queue
without removing it. It returns null if the queue is empty.
element()- This method is similar to peek(). It
throws NoSuchElementException when the queue is empty.
poll()- This method removes and returns the head of the
queue. It returns null if the queue is empty.
remove()- removes and returns the head of the queue. It
throws NoSuchElementException when the queue is empty.
Java Programming RAGHU ENGINEERING COLLEG 85
Queue
Example Snippet:
Queue<String> queue=new LinkedList<String>(); Output:
[Link]("C"); [Link]("CPP"); head:C
[Link]("Python"); [Link]("Java"); head:C
[Link]("head:"+[Link]()); C
[Link]("head:"+[Link]()); CPP
Iterator itr=[Link](); Python
while([Link]()) Java
[Link]([Link]()); C
[Link]([Link]()); CPP
[Link]([Link]());
Java Programming RAGHU ENGINEERING COLLEG 86
Maps
The [Link] interface represents a mapping between a
key and a value. The Map interface is not a subtype of
the Collection interface. Therefore it behaves a bit different
from the rest of the collection types.

Java Programming RAGHU ENGINEERING COLLEG 87


Maps
• A Map cannot contain duplicate keys and each key can map
to at most one value. Some implementations allow null key
and null value like the HashMap and LinkedHashMap, but
some do not like the TreeMap.

• The order of a map depends on specific implementations,


e.g TreeMap and LinkedHashMap have predictable order,
while HashMap does not.

• There are two interfaces for implementing Map in java:


Map and SortedMap, and three
classes: HashMap, TreeMap and LinkedHashMap.
Java Programming RAGHU ENGINEERING COLLEG 88
Maps
classes that implement Map Interface:

HashMap:
HashMap is the implementation of Map, but it doesn't
maintain any order.

LinkedHashMap:
LinkedHashMap is the implementation of Map. It inherits
HashMap class. It maintains insertion order.

TreeMap:
TreeMap is the implementation of Map and SortedMap. It
maintains ascending order.
Java Programming RAGHU ENGINEERING COLLEG 89
Maps: Creation
Syntax for creation of map:
Map< key_type,value_type> obj =
new HashMap< key_type,value_type>();
or
Map< key_type,value_type> obj =
new LinkedHashMap< key_type,value_type>();
or
Map< key_type,value_type> obj =
new TreeMap< key_type,value_type>();

put() method:
put(key, value): This method is used to insert an entry into
map.
Java Programming RAGHU ENGINEERING COLLEG 90
Maps: Creation Example
Example Snippet:
Map< Integer,Integer> hm =
new HashMap< Integer,Integer>();
[Link](2, new Integer(300));
[Link](1, new Integer(200)); Output:
{1=200, 2=300, 3=400}
[Link](3, new Integer(400));
[Link](hm);

// Try creation of LinkedHashMap and TreeMap


// Also try String type keys.

Java Programming RAGHU ENGINEERING COLLEG 91


Maps: Methods
putAll(Map map):
This method is used to insert the specified map in this map.

public Object remove(key):


This method is used to delete an entry for the specified key.

public Object get(key):


This method is used to return the value for the specified key.

public boolean containsKey(key):


This method is used to search the specified key from this
map.
.
Java Programming RAGHU ENGINEERING COLLEG 92
Maps: Methods
public object getKey() It is used to obtain a key.

public object getValue() It is used to obtain value.

public Set keySet(): This method is used to return the Set view
containing all the keys.

The [Link] interface enables you to work with a map entry.

public Set entrySet(): This method is used to return the Set view
containing all the keys and values. This method is given by
[Link] interface.

program to demonstrate map methods


Java Programming RAGHU ENGINEERING COLLEG 93
Dictionary

• [Link] is an abstract class, representing a key-


value relation and works similiar to a map. Given a key you
can store values and when needed can retrieve the value
back using its key. Thus, it is a list of key-value pair.

• The Dictionary class is the abstract parent of any class, such


as Hashtable, which maps keys to values.

Java Programming RAGHU ENGINEERING COLLEG 94


Iterable
The Java Iterable interface ([Link]) is one of the
root interfaces of the Java Collections API. A class that
implements the Java Iterable interface can be iterated with
the Java for-each loop.

The Collection interface extends Iterable, so all subtypes


of Collection also implement the Iterable interface. For
instance, both the Java List and Set interfaces extend
the Collection interface, and thereby also
the Iterable interface.

An object of a class that implements the Iterable can be used


with the Java for-each loop.
Java Programming RAGHU ENGINEERING COLLEG 95
Iterable
Example Snippet:
ArrayList list = new ArrayList();
[Link]("one");
[Link]("two"); Output:
[Link]("three"); one
for(Object o : list) two
{ three
[Link](o);
}

Java Programming RAGHU ENGINEERING COLLEG 96


HashTable
•Java Hashtable class implements a hashtable, which maps
keys to values. It inherits Dictionary class and implements
the Map interface.

•It is similar to HashMap, but is synchronised.

•Hashtable stores key/value pair in hash table.

•In Hashtable we specify an object that is used as a key, and


the value we want to associate to that key. The key is then
hashed, and the resulting hash code is used as the index at
which the value is stored within the table.

Java Programming RAGHU ENGINEERING COLLEG 97


HashTable
Constructors:

Hashtable(): This is the default constructor.

Hashtable(int size): This creates a hash table that has initial


size specified by size.

Hashtable(int size, float fillRatio): fill ratio determines


how full hash table can be before it is resized upward and its
value lies between 0.0 to 1.0

Hashtable(Map m): This creates a hash table that is


initialized with the elements in m.
Java Programming RAGHU ENGINEERING COLLEG 98
HashTable: Creation
Example Snippet:
Hashtable<Integer, String> h =
new Hashtable<Integer, String>();
[Link](3, "cse");
[Link](2, "ece");
[Link](1, "mech");
[Link](h);

Output:
{3=cse, 2= ece, 1=mech}

Java Programming RAGHU ENGINEERING COLLEG 99


HashTable: Methods
some important methods in HashTable:

put() putAll() remove() size()

void clear() : method clears the hashtable so that it contains


no keys.

boolean containsKey(Object key): tests if some key maps


into the specified value in this hashtable.

boolean containsValue(Object value): returns true if this


hash table maps one or more keys to this value.

Java Programming RAGHU ENGINEERING COLLEG 100


HashTable: Methods
entrySet() : used to get a set view of the entries contained in
this hash table.

keySet() :used to get a Set view of the keys contained in this


hash table.

Object get(Object key) : used to get the object that contains


the value associated with key.

boolean isEmpty() :used to test if this hashtable maps no


keys to values.

Java Programming RAGHU ENGINEERING COLLEG 101

You might also like