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

AR20 JP Unit-4

The document discusses multithreading in Java, including thread life cycles, creation of threads, and thread priorities. It covers the 5 states of a thread's life cycle - New, Runnable, Running, Non-Runnable (Blocked), and Terminated. Threads can be created by extending the Thread class or implementing the Runnable interface. Methods like start(), sleep(), join(), getPriority(), and setPriority() are used to control threads.

Uploaded by

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

AR20 JP Unit-4

The document discusses multithreading in Java, including thread life cycles, creation of threads, and thread priorities. It covers the 5 states of a thread's life cycle - New, Runnable, Running, Non-Runnable (Blocked), and Terminated. Threads can be created by extending the Thread class or implementing the Runnable interface. Methods like start(), sleep(), join(), getPriority(), and setPriority() are used to control threads.

Uploaded by

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

UNIT IV

Multithreading: introduction, thread life cycle, creation of threads, thread priorities,


thread synchronization, communication between threads. Reading data from files and
writing data to files, random access file. Collections: Collections Hierarchy; List -
ArrayList, LinkedList;

Sets - HashSet, TreeSet, LinkedHashSet; Queue; Maps - HashMap, TreeMap,


LinkedHashMap; Iterable, Iterator

4.1 Multithreading: introduction


Multithreading in java is a process of executing multiple threads simultaneously.
 Multiprocessing and multithreading, both are used to achieve multitasking.
 But we use multithreading than multiprocessing because threads share a
common memory area.
 They don't allocate separate memory area so saves memory, and context-
switching between the threads takes less time than process.
 Java Multithreading is mostly used in games, animation etc.

Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use
multitasking to utilize the
CPU. Multitasking can be achieved by two ways:
1. Process-based Multitasking (Multiprocessing)
2. Thread-based Multitasking (Multithreading)
1) Process-based Multitasking (Multiprocessing)
 Each process has its own address in memory i.e., each process allocates
separate memory area.
 Process is heavyweight.
 Cost of communication between the processes is high.
 Switching from one process to another require some time for saving and
loading registers, memory maps, updating lists etc.
2) Thread-based Multitasking (Multithreading)
 Threads share the same address space.
 Thread is lightweight.
 Cost of communication between the thread is low.
4.2 thread life cycle
Thread
A thread is a lightweight sub process, a smallest unit of processing. It is a separate path
of execution. Threads are independent, if there occurs exception in one thread, it
doesn't affect other threads. It shares a common memory area.

Thread States
A thread can be in one of the five states. According to sun, there are only 4 states in
thread life cycle in java new, runnable, non-runnable and terminated. There is no
running state. But for better understanding the threads, we are explaining it in the 5
states.

The life cycle of the thread in java is controlled by JVM. The java thread states are as
follows:
1. New 4. Non-Runnable (Blocked)
2. Runnable 5. Terminated
3. Running

1) New
The thread is in new state if we create an instance of Thread class but before the invocation
of start () method.
 A thread enters the newly created by using a new operator.
 It is new state or born state immediately after creation. i.e. when a constructor is
called the Thread is created but is not yet to run() method will not begin until it
start() method is called.
 After the start() method is called, the thread will go to the next state, Runnable
state.

2) Runnable
The thread is in runnable state after invocation of start () method, but the thread scheduler
has not selected it to be the running thread.
 Once we invoke the start() method, the thread is runnable.
3) Running
The thread is in running state if the thread scheduler has selected it.
It is divided into two states:
The running states
• When the thread is running state, it assigned by CPU cycles and is actually running.
The Queued state.
• When the thread is in Queued state, it is waiting in the Queue and competing for its
turn to spend CPU cycles
• It is controlled by Virtual Machine Controller.
• When we use yield() method it makes sure other threads of the same priority have
chance to run.
• This method causes voluntary move itself to the queued state from the running state.

4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.

The blocked state is entered when one of the following events occurs:
• The thread itself or another thread calls the suspend() method (it is deprecated)
• The thread calls an object’s wait() method
• The thread itself calls the sleep() method.
• The thread is waiting for some I/O operations to complete.
• The thread will join() another thread.

5) Terminated
A thread is in terminated or dead state when its run() method exits.

A thread is dead for any one of the following reasons:


• It dies a natural death because the run method exists normally.
• It dies abruptly because an uncaught exception terminates the run method.
• In particular stop() is used to kill the thread. This is depricated.
• To find whether thread is alive i.e. currently running or blocked
Use isAlive() method
• If it returns true the thread is alive

4.3 creation of threads


How to create thread
There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface.
Thread class Runnable interface.
Thread class provide constructors and The Runnable interface should be
methods to create and perform implemented by any class whose
operations on a thread. Thread instances are intended to be executed
class extends Object class and by a thread. Runnable interface
implements Runnable interface. have only one method named run ().
Commonly used Constructors of Thread public void run(): is used to perform
class: action for a thread
 Thread()
 Thread(String name)
 Thread(Runnable r)
 Thread(Runnable r, String name)

Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs following
tasks:
 A new thread starts (with new call stack).
 The thread moves from new state to the Runnable state.
 When the thread gets a chance to execute, its target run() method will run.

Commonly used methods of Thread class:


1. public void run(): is used to perform action for a thread.
2. public void start(): starts the execution of the thread. JVM calls the run() method
on the thread.
3. public void sleep(long miliseconds): Causes the currently executing thread to
sleep (temporarily cease execution) for the specified number of milliseconds.
4. public void join(): waits for a thread to die.
5. public void join(long miliseconds): waits for a thread to die for the specified
miliseconds.
6. public int getPriority(): returns the priority of the thread.
7. public int setPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the thread.
10. public Thread currentThread(): returns the reference of currently executing thread.
11. public int getId(): returns the id of the thread.
12. public Thread.State getState(): returns the state of the thread.
13. public boolean isAlive(): tests if the thread is alive.
14. public void yield(): causes the currently executing thread object to temporarily
pause and allow other threads to execute.
15. public void suspend(): is used to suspend the thread(depricated).
16. public void resume(): is used to resume the suspended thread(depricated).
17. public void stop(): is used to stop the thread(depricated).
18. public boolean isDaemon(): tests if the thread is a daemon thread.
19. public void setDaemon(boolean b): marks the thread as daemon or user thread.
20. public void interrupt(): interrupts the thread.
21. public boolean isInterrupted(): tests if the thread has been interrupted.
22. public static boolean interrupted(): tests if the current thread has been interrupted
Java Thread Example by extending Java Thread Example by implementing
Thread class Runnable interface
class Test extends Thread{ class Test implements Runnable{
public void run(){ public void run(){
System.out.printl(“Thread is running…”); System.out.println(“Thread is running…”);
} }
public static void main(string args[]){ public static void main(String args[]){
Test t1 = new Test(); Test t1 = new Test():
t1.start(): Thread th = new Thread(t1);
} Th.start():
} }
}

If we are not extending the Thread class, our class object would not be treated as a thread
object. So, we need to explicitly create Thread class object. We are passing the object of our
class that implements Runnable so that class run() method may execute.

Naming Thread and Current Thread


Naming Thread
The Thread class provides methods to change and get the name of a thread. By default,
each thread has a name i.e. thread-0, thread-1 and so on. But we can change the name of
the thread by using setName() method. The syntax of setName() and getName() methods
are given below:
 public String getName(): is used to return the name of a thread.
 public void setName(String name): is used to change the name of a thread.

public class ThreadNameDemo{


public static void main(String args[]){
System.out.println(“Hello”);
System.out.println(Thread.currentThread().getName());
Thread.currentThread().setName(“JP”);
System.out.println(“New Thread Name: “+Thread.currentThread().getName());
}
}
public class ThreadNameDemo{
public static void main(String args[]){
System.out.println(Thread.currentThread().setName(“Sun Mircosystem”));
System.out.println(“Main Thread Name: “+Thread.currentThread().getName());
}
}
Current Thread
The currentThread() method returns a reference of currently executing thread.
Example of currentThread () method
Public class Test extends Thread{
Public void run(){
System.out.println(“Thread Task is executed by:” + Thread.currentThread().getName());
}
Public static void main(String args[]){
System.out.println(“Hello is printed by: ” +Thread.currentThread().getName());

Test t = new Test();


t.setName(“Sun”);
t.start();

Test t1= new Test();


t1.setName(“Oracle”);
t1.start();
}
}
public class Test extends Thread{
public void run(){
Thread.currentThread().setName(“Sun”);
System.out.println(“Thread Task is executed by:” + Thread.currentThread().getName());
}
Public static void main(String args[]){
System.out.println(“Hello is printed by: ” +Thread.currentThread().getName());

Test t = new Test();


t.start();
System.out.println(Thread.currentThread().isAlive()):
System.out.println(t.isAlive()):
}
}

4.4 thread priorities


Priority of a Thread (Thread Priority):
Each thread has a priority. Priorities are represented by a number between 1 and 10. In most
cases, thread schedular schedules the threads according to their priority (known as
preemptive scheduling). But it is not guaranteed because it depends on JVM specification that
which scheduling it chooses.

3 constants defined in Thread class:


1. public static int 2. public static int 3. public static int
MIN_PRIORITY NORM_PRIORITY MAX_PRIORITY
Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the
value of MAX_PRIORITY is 10.

Example of priority of a Thread:


class MultiPriority extends Thread {
public void run(){
System.out.println(“running thread name is: “ +Thread.currentThread().getName());
System.out.println(“running thread priority is: “ +Thread.currentThread().getPriority());
}
public static void main(String args[]){
MultiPriority mp = new MultiPriority();
MultiPriority mp1 = new MultiPriority();
mp.setPriority(Thread.MIN_PRIORITY):
mp1.setPriority(Thread.MAX_PRIORITY);
mp.start();
mp1.start();
}
}

Daemon Thread in Java


Daemon thread in java is a service provider thread that provides services to the user thread. Its
life depend on the mercy of user threads i.e. when all the user threads dies, JVM terminates this
thread automatically. There are many java daemon threads running automatically e.g. gc,
finalizer etc. You can see all the detail by typing the jconsole in the command prompt. The
jconsole tool provides information about the loaded classes, memory usage, running threads
etc.

 It provides services to user threads for background supporting tasks. It has no role in life
than to serve user threads.
 Its life depends on user threads.
 It is a low priority thread.

Why JVM terminates the daemon thread if there is no user thread?


The sole purpose of the daemon thread is that it provides services to user thread for background
supporting task. If there is no user thread, why should JVM keep running this thread. That is why
JVM terminates the daemon thread if there is no user thread.

Methods for Java Daemon thread by Thread class


The java.lang.Thread class provides two methods for java daemon thread.
Method Description
public void setDaemon(boolean status) is used to mark the current thread as
daemon thread or user thread.
public boolean isDaemon() is used to check that current is daemon
class DaemonThread extends Thread
{
public void run()
{
// Checking whether the thread is Daemon or not
if(Thread.currentThread().isDaemon())
System.out.println("Daemon thread working...");
else
System.out.println("User thread is working...");
}
public static void main(String[] args)
{

DaemonThread t1 = new DaemonThread();


DaemonThread t2 = new DaemonThread();
t1.setDaemon(true); // Setting user thread t1 to Daemon
t1.start();
t2.start();
}
}

Synchronization
Synchronization is a process that involves coordinating the execution of multiple threads to
ensure a desired outcome without corrupting the shared data and preventing any occurrence
of deadlocks and race conditions.

Java Synchronization is better option where we want to allow only one thread to access the
shared resource.
The synchronization is mainly used to:
 To prevent thread interference.
 To prevent consistency problem.

Note: A race condition is an undesirable situation that occurs when a device or system
attempts to perform two or more operations at the same time, but because of the nature
of the device or system, the operations must be done in the proper sequence to be done
correctly.

Synchronization is built around an internal entity known as the lock or 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.

All other threads attempting to enter the locked 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 reenter the same monitor if it so desires.
Limitations
1. Concurrency Limitations: Java synchronization does not allow concurrent reads.
2. Decreases Efficiency: Java synchronized method run very slowly and can degrade
the performance,

Types of Synchronization: There are two types of synchronization


1. Process Synchronization
2. Thread Synchronization

Thread Synchronization
There are two types of thread synchronization
1. Mutual exclusive
2. Inter-thread communication.

Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing data.
This can be done by two ways in java:
1. by synchronized method
2. by synchronized block

synchronized method
The synchronized keyword in java creates a block of code referred to as critical section. If you
declare any method as synchronized, it is known as synchronized method. Synchronized
method is used to lock an object for any shared resource.

synchronized public return-type method_name( parameter-list)


{
//statement to be synchronized
}
When a thread invokes a synchronized method, it automatically acquires the lock for that
object and releases it when the thread completes its task.

class Table
{
synchronized void printTable(int n) //synchronized method
{
for(int i=1;i<=10;i++)
{
System.out.println(n+"x"+i+"="+(n*i));
try
{
Thread.sleep(400);
}catch(InterruptedException e)
{
System.out.println(e);
}
}
}
}
class MyThread1 extends Thread
{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(2);
}
}
class MyThread2 extends Thread
{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(3);
}
}

public class Synchronization


{
public static void main(String args[])
{
Table tbl = new Table(); //only one object
MyThread1 t1=new MyThread1(tbl);
MyThread2 t2=new MyThread2(tbl);
t1.start();
t2.start();
}
}
synchronized block
Synchronized block can be used to perform synchronization on any specific resource of the
method. Its general form is:

synchronized (object)
{
//statement to be synchronized
}

Here, object is a reference to the object being synchronized. A synchronized block ensures
that a call to a synchronized method that is a member of object’s class occurs only after the
current thread has successfully entered object’s monitor.

Suppose you have 100 lines of code in your method, but you want to synchronize only 5
lines, you can use synchronized block. If you put all the codes of the method in the
synchronized block, it will work same as the synchronized method.

class Table
{
void printTable(int n)
{
for(int i=1;i<=10;i++)
{
System.out.println(n+"x"+i+"="+(n*i));
try
{
Thread.sleep(400);
}catch(InterruptedException e)
{
System.out.println(e);
}
}
}
}

class MyThread1 extends Thread


{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run()
{
synchronized(t) //synchronized block
{
t.printTable(2);
}
}
}
class MyThread2 extends Thread
{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
synchronized(t) //synchronized block
{
t.printTable(4);
}
}
}
public class Sync {
public static void main(String args[])
{
Table tbl = new Table(); //only one object
MyThread1 t1=new MyThread1(tbl);
MyThread2 t2=new MyThread2(tbl);
t1.start();
t2.start();
}
}

Inter-thread communication
It is all about allowing synchronized threads to communicate with each other. Inter-thread
communication is a mechanism in which a thread is paused running in its critical section and
another thread is allowed to enter (or lock) in the same critical section to be executed. It is
implemented by following methods of Object class:
1. wait()
2. notify()
3. notifyAll()

wait() method
It tells the calling thread to give up the monitor and go to sleep until some other thread enters
the same monitor and calls notify( ) or notifyAll( ), or a specified amount of time has elapsed.
The current thread must own this object's monitor, so it must be called from the synchronized
method only otherwise it will throw exception. Its general form is:
Method Description
public final void wait()throws InterruptedException waits until object is notified.

public final void wait(long timeout)throws waits for the specified amount of
InterruptedException time.

notify() method
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on
this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the
discretion of the implementation.
Its general form is:
public final void notify( )

notifyAll( ) method
It wakes up all the threads that called wait( ) on the same object. One of the threads
will be granted access. Its general form is:
public final void notifyAll( )

Difference between wait and sleep?


wait() method releases the lock sleep() method doesn't release the lock.
is the method of Object class is the method of Thread class
is the non-static method is the static method
is the non-static method is the static method
should be notified by notify() or notifyAll() after the specified amount of time, sleep is
methods completed.

Example of inter thread communication in java


class MyThread extends Thread{
int total = 0;
public void run() {
synchronized(this) {
for(int i=0;i<=10;i++) {
total=total+i;
this.notify();
}
}
}
}
public class Sampe {
public static void main(String[] args) {
MyThread t = new MyThread();
t.start();
try {
synchronized(t) {
t.wait();
System.out.println("Total: " +t.total);
}
}
catch(Exception e) {
e.printStackTrace();
}
}
}

Reading data from files and writing data to files,


Java.io is a package which contains number of classes by using that class we are able to send
the data from one place to another place.

In java language we are transferring the data in the form of two ways: -
1. Byte format 2. Character format

Stream/channel: -
Types of Streams
In general, streams are classified into two types known as character streams and the byte
streams. The java.io package provides two sets of class hierarchies to handle character and
byte streams for reading and writing:

1. Input Stream and Output Stream classes are operated on bytes for reading and writing,
respectively.
2. Reader and Writer classes are operated on characters for reading and writing,
respectively.
3. There are two other classes that are useful for handling input and output. These are
File class and Random-Access File class.

The java.io package contains a large number of stream classes that provide capabilities for
processing all types of data. These classes may be categorized into two groups based on the
data type on which they operate.
1. Byte oriented streams. (Supports byte formatted data to transfer)
2. Character oriented stream. (Supports character formatted data to transfer)
Byte oriented streams: -
Java.io.FileInputStream

To read the data from the destination file to the java application we have to use FileInputSream
class.
 It’s an abstract class.
 It is a superclass of all binary stream representing inputs.
 It gets the input data from data source and gives to the program.
 A data source can be a file, a string, or memory – anything that can contain data.

To read the data from the .txt file we have to read() method.
 public abstract int read() throws IOException
 public int read(byte[] b) throws IOException
 public int read(byte[] b, int off, int len) throws IOException
 public long skip(long n) throws IOException
 public int available() throws IOException
 public void close() throws IOException
 public void mark(int readlimit)
 public void reset() throw IOException
 public boolean markSupported()

Java.io.FileOutputStream: -
To write the data to the destination file we have to use the FileOutputStream.
 It’s an abstract class.
 It is a superclass of all binary stream representing outputs.
 It accepts output bytes and sends them to the data sink.
 A data sink can be a file, a string, or memory – anything that can contain data.
 It inherits Flushable interface.

To write the data to the destination file we have to use write() method.
 public void write(int) throws IOException
 public void write(byte[]) throws IOException
 public void write(byte[], int offser, int len) throws IOException
 public void flush()throws IOException
 public void close() throws IOException
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

//import java.io.*;
class InputStreamOutputStreamDemo{
public static void main(String [] args){
try{
File f = new File("D://Test//WelcomeScan.webp");
//create inputstream WelcomeScan
FileInputStream input = new FileInputStream(f);
byte b[] = new byte[(int)f.length()];
int numBytes = input.read(b);
System.out.println("Data from File Read Successfully...");

FileOutputStream output = new FileOutputStream("D://test//output.jpg");


output.write(b);
System.out.println("Data Written to File Successfully");
}
catch(IOException e){
System.out.println("Exception Occurred");
}
}
}

Writer
 It is an abstract class for writing to character streams.
 The methods that a subclass must implement are write(char[], int, int), flush(), and
close().
 Most subclasses will override some of the methods defined here to provide higher
efficiency, functionality or both.
Constructor
Constructor Description
Writer() It creates a new character-stream writer whose critical
sections will synchronize on the writer itself.
Writer(Object lock) It creates a new character-stream writer whose critical
sections will synchronize on the given object.

Methods
Method Description
Writer append(char c) It appends the specified character to this writer.
Writer append(CharSequence csq) It appends the specified character sequence to this
writer
Writer append(CharSequence csq, It appends a subsequence of the specified character
int start, int end) sequence to this writer
abstract void close() It closes the stream, flushing it first.
abstract void flush() It flushes the stream.
void write(char[] cbuf) It writes an array of characters.
abstract void write(char[] cbuf, int It writes a portion of an array of characters.
off, int len)
void write(int c) It writes a single character
void write(String str) It writes a string.
void write(String str, int off, int len) It writes a portion of a string.

Reader
 Java Reader is an abstract class for reading character streams.
 The only methods that a subclass must implement are read(char[], int, int) and close().
 Most subclasses, however, will override some of the methods to provide higher
 efficiency, additional functionality, or both.
 Some of the implementation classes are BufferedReader, CharArrayReader, FilterReader,
InputStreamReader, PipedReader, StringReader

Constructor
Constructor Description
protected Reader() It creates a new character-stream reader whose critical
sections will synchronize on the reader itself.
protected Reader(Object lock) It creates a new character-stream reader whose critical
sections will synchronize on the given object.

Methods:
Method Description
abstract void close() It closes the stream and releases any system
resources associated with it.
void mark(int readAheadLimit) It marks the present position in the stream.
boolean markSupported() It tells whether this stream supports the mark()
operation.
int read() It reads a single character.
int read(char[] cbuf) It reads characters into an array.
abstract int read(char[] cbuf, int off, int It reads characters into a portion of an array.
len)
int read(CharBuffer target) It attempts to read characters into the specified
character buffer.
boolean ready() It tells whether this stream is ready to be read.
void reset() It resets the stream.
long skip(long n) It skips characters.
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

class FileReaderFileWriterDemo{
public static void main(String [] args){
FileReader fin;
FileWriter fout;
int c;

if(args.length != 2){
System.out.println("Please Provide 2 File Names");
return;
}

try{
fin = new FileReader(args[0]);
fout = new FileWriter(args[1]);

do{
c = fin.read();
if (c != -1)
fout.write(c);
}while(c != -1);

System.out.println("File Copied SuccessFully");


fin.close();
fout.close();
}
catch(IOException ioe){
System.out.println("Exception Occurred While Processing");
}
}
}

random access file.


Java RandomAccessFile provides facility to both read and write data to a file.

RandomAccessFile works with file as large array of bytes stored in the file system and a cursor
using which we can move the file pointer position.

RandomAccessFile class is part of Java IO. While creating the instance of RandomAccessFile in
java, we need to provide the mode to open the file. For example, to open the file for read only
mode we have to use “r” and for read-write operations we have to use “rw”.
Using file pointer, we can read or write data from random access file at any position. To get the
current file pointer, you can call getFilePointer () method and to set the file pointer index, you
can call seek (int i) method.
If we write data at any index where data is already present, it will override it.

Java RandomAccessFile read example


We can read byte array from a file using RandomAccessFile in java. Below is the pseudo code
to read file using RandomAccessFile.
RandomAccessFile raf = new RandomAccessFile("file.txt", "r");
raf.seek(1);
byte[] bytes = new byte[5];
raf.read(bytes);
raf.close();
System.out.println(new String(bytes));

In first line, we are creating RandomAccessFile instance for file in read-only mode.
In second line, we are moving the file pointer to index 1.
We have created byte array of length 5, so when we are calling read(bytes) method then 5
bytes are read from file to the byte array.
Finally, we are closing the RandomAccessFile resource and printing the byte array to console.

Java RandomAccessFile write example


Here is a simple example showing how to write data to a file using RandomAccessFile in java.
RandomAccessFile raf = new RandomAccessFile("file.txt", "rw");
raf.seek(5);
raf.write("Data".getBytes());
raf.close();

Since RandomAccessFile treats file as byte array, write operation can override the data as well
as it can append to a file. It all depends on the file pointer position. If the pointer is moved
beyond the file length and then write operation is called, then there will be junk data written in
the file. So, you should take care of this while using write operation.

RandomAccessFile append example


All we need is to make sure file pointer is at the end of file to append to a file. Below is the
code for append to file using RandomAccessFile.
RandomAccessFile raf = new RandomAccessFile("file.txt", "rw");
raf.seek(raf.length());
raf.write("Data".getBytes());
raf.close()
import java.io.RandomAccessFile;
import java.io.IOException;

class RandomAccessDemo{
public static void main(String [] args){
try{
String filePath = args[0];
RandomAccessFile rafile = new RandomAccessFile(filePath,"rw");
byte [] data = new byte[(int) rafile.length()];
rafile.read(data);

System.out.println("The Original Content of File:\n" + new String(data));

rafile.seek(rafile.length());
rafile.write("This is the content written from the program\n".getBytes());
rafile.write("I Want to append the content".getBytes());
rafile.seek(0);

data = new byte[(int) rafile.length()];


rafile.read(data);
System.out.println("Modified Content:\n");
System.out.println(new String(data));

/*rafile.seek(0);
rafile.write("This is the content written from the program\n".getBytes());
rafile.write("I Want to change the content".getBytes());
rafile.seek(0);

data = new byte[(int) rafile.length()];


rafile.read(data);
System.out.println("Modified Content:\n");
System.out.println(new String(data));*/

}
catch(IOException ioe){
ioe.printStackTrace();
}
}
}
Collections:
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.

The Collection 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 achieved by Java Collections.

Java Collection 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.).

The Collection interface (java.util.Collection) and Map interface (java.util.Map) are the two main
“root” interfaces of Java collection classes.

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.

Accessing elements of these Data Structures was a hassle as each had a different method (and
syntax) for accessing its members.

Advantages of Collection Framework:


1. Consistent API: The API has a basic set of interfaces like Collection, Set, List, or Map. All
classes (ArrayList, LinkedList, Vector, etc..,) that implement these interfaces have some
common set of methods.

2. Reduces programming effort: A programmer doesn’t have to worry about the design
of Collection, and he can focus on its best use in his program.

3. Increases program speed and quality: Increases performance by providing high


performance implementations of useful data structures and algorithms.
Collections Hierarchy; List –

Core Interfaces in Collections


Note that this diagram only shows core interfaces.
1. Collection: Root interface with basic methods like add(), remove(), contains(), isEmpty(),
addAll(), ... etc.

2. Set: Doesn't allow duplicates. Example implementations of Set interface are HashSet
(Hashing based) and TreeSet (balanced BST based). Note that TreeSet implements
SortedSet.

3. List: Can contain duplicates and elements are ordered. Example implementations are
LinkedList (linked list based) and ArrayList (dynamic array based)

4. Queue: Typically order elements in FIFO order except exceptions like PriorityQueue.
Deque: Elements can be inserted and removed at both ends. Allows
both LIFO and FIFO.

5. Map: Contains Key value pairs. Doesn't allow duplicates. Example implementation are
HashMap and TreeMap.TreeMap implements SortedMap.

The difference between Set and Map interface is that in Set we have only keys, whereas in Map,
we have key, value pairs.
Java ArrayList class
Java ArrayList class uses a dynamic array for storing the elements. It inherits AbstractList
class and implements List interface.
The important points about Java ArrayList class are:

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

Hierarchy of ArrayList class


As shown in above diagram, Java ArrayList class extends AbstractList class which implements List
interface. The List interface extends Collection and Iterable interfaces in hierarchical order.

ArrayList class declaration


Let's see the declaration for java.util.ArrayList class.
1. public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess,
Cloneable, Serializable

Constructors of Java ArrayList


Constructor Description
ArrayList() It is used to build an empty array list.
ArrayList(Collection c) It is used to build an array list that is initialized
with the elements of the collection c.
ArrayList(int capacity) It is used to build an array list that has the
specified initial capacity.

Methods of Java ArrayList


Method Description
void add(int index, Object element) It is used to insert the specified element at the specified
position index in a list.
boolean addAll(Collection c) It is used to append 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.
void clear() It is used to remove all of the elements from this list.
int lastIndexOf(Object o) It is used to return the index in this list of the last
occurrence of the specified element, or -1 if the list does
not contain this element.
Object[ ] toArray() It is used to return an array containing all of the
elements in this list in the correct order.
Object[ ]toArray(Object[ ] a) It is used to return an array containing all of the
elements in this list in the correct order
boolean add(Object o) It is used to append the specified element to the end of
a list.
boolean addAll(int index, It is used to insert all of the elements in the specified
Collection c) collection into this list, starting at the specified position.
Object clone() It is used to return a shallow copy of an ArrayList.
int indexOf(Object o) It is used to return the index in this list of the first
occurrence of the specified element, or -1 if the List does
not contain this element.
void trimToSize() It is used to trim the capacity of this ArrayList instance
to be the list's current size.

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.

Let's see the old non-generic example of creating java collection.

1. ArrayList al=new ArrayList();//creating old non-generic arraylist

Let's see the new generic example of creating java collection.

1. ArrayList<String> al=new ArrayList<String>();//creating new generic arraylist

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.
import java.util.*;
class TestCollection1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Ravi");//Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
//Traversing list through Iterator
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}

Two ways to iterate the elements of collection in java


There are two ways to traverse collection elements:
1. By Iterator interface. 2. By for-each loop.
In the above example, we have seen traversing ArrayList by Iterator. Let's see the example to
traverse ArrayList elements using for-each loop.
import java.util.*;
class TestCollection2{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
for(String obj:al)
System.out.println(obj);
}
}
Java LinkedList class

Java LinkedList class uses doubly linked list to store the elements. It provides a linked-list
data structure. It inherits the AbstractList class and implements List and Deque interfaces.

The important points about Java LinkedList are:


 Java LinkedList class can contain duplicate elements.
 Java LinkedList class maintains insertion order.
 Java LinkedList class is non synchronized.
 In Java LinkedList class, manipulation is fast because no shifting needs to be
occurred.
 Java LinkedList class can be used as list, stack or queue.
Hierarchy of LinkedList class
As shown in above diagram, Java LinkedList class extends AbstractSequentialList class and
implements List and Deque interfaces.
Doubly Linked List
In case of doubly linked list, we can add or remove elements from both side

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


Method Description
LinkedList() It is used to construct an empty list.
LinkedList(Collection c) It is used to construct a list containing the elements of the
specified collection, in the order they are returned by the
collection's iterator.
Methods of Java LinkedList
Method Description
void add(int index, It is used to insert the specified element at the specified
Object element) position index in a list.
void addFirst(Object o) It is used to insert the given element at the beginning of a
list.
void addLast(Object o) It is used to append the given element to the end of a list.
int size() It is used to return the number of elements in a list
boolean add(Object o) It is used to append the specified element to the end of a
list.
boolean contains(Object o) It is used to return true if the list contains a specified element.
boolean remove(Object o) It is used to remove the first occurence of the specified
element in a list.
Object getFirst() It is used to return the first element in a list.
Object 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 occurrence
of the specified element, 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 occurrence
of the specified element, or -1 if the list does not contain
any element.

Java LinkedList Example


import java.util.*;
public class TestCollection7{
public static void main(String args[]){
LinkedList<String> al=new LinkedList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Difference between ArrayList and LinkedList
ArrayList and LinkedList both implements List interface and maintains insertion order. Both
are non synchronized classes.

ArrayList LinkedList
ArrayList internally uses dynamic array to LinkedList internally uses doubly linked list to
store the elements. store the elements.
Manipulation with ArrayList is slow because it Manipulation with LinkedList is faster than
internally uses array. If any element is ArrayList because it uses doubly linked list so
removed from the array, all the bits are no bit shifting is required in memory.
shifted in memory.
ArrayList class can act as a list only because it LinkedList class can act as a list and
implements List only. queue both because it implements List
and Deque interfaces.
ArrayList is better for storing and accessing LinkedList is better for manipulating data.
data.

Example of ArrayList and LinkedList in Java


import java.util.*;
class TestArrayLinked{
public static void main(String args[]){

List<String> al=new ArrayList<String>();//creating arraylist


al.add("Ravi");//adding object in arraylist
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");

List<String> al2=new LinkedList<String>();//creating linkedlist


al2.add("James");//adding object in linkedlist
al2.add("Serena");
al2.add("Swati");
al2.add("Junaid");

System.out.println("arraylist: "+al);
System.out.println("linkedlist: "+al2);
}
}
Set:
Set is a collection that does not contain duplicates. Set collection in java.util models the
mathematical concept set. The concepts of union, intersection, and the difference of a set are
available in the Set interface and supported by its subclasses. We will discuss two classes under
this interface, i.e., HashSet and TreeSet. TreeSet is a sorted collection as it inherits the SortedSet
interface (sub-interface of Set), whereas HashSet is not a sorted collection. HashSet uses the
concept of hashing.

Java HashSet class

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.

The important points about Java HashSet class are:


 HashSet stores the elements by using a mechanism called hashing.
 HashSet contains unique elements only.

Difference between List and Set


List can contain duplicate elements whereas Set contains unique elements only.

Hierarchy of HashSet class


The HashSet class extends AbstractSet class which implements Set interface. The Set interface
inherits Collection and Iterable interfaces in hierarchical order.

HashSet class declaration


Let's see the declaration for java.util.HashSet class.
1. public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable,
Serializable

Constructors of Java HashSet class


Constructor Description
HashSet() It is used to construct a default HashSet.
HashSet(int capacity) It is used to initialize the capacity of the hash set to the given
integer value capacity. The capacity grows automatically as
elements are added to the HashSet
HashSet(int capacity, It is used to initialize the capacity of the hash set to the given
float loadFactor) integer value capacity and the specified load factor.
HashSet(Collection c) It is used to initialize the hash set by using the elements of the
collection c.

Methods of Java HashSet class


Various methods of Java HashSet class are as follows:
Method Description
boolean add(Object o) It is used to adds the specified element to this set if it is not
already present.
void clear() It is used to remove all of the elements from this set.
object clone() It is used to return a shallow copy of this HashSet instance:
the elements themselves are not cloned.
boolean contains(Object o) It is used to return true if this set contains the specified
element.
boolean isEmpty() It is used to return true if this set contains no elements
Iterator<E> iterator() It is used to return an iterator over the elements in this set.
boolean remove(Object o) It is used to remove the specified element from this set if it
is present.
int size() It is used to return the number of elements in this set.
Spliterator<E> spliterator() It is used to create a late-binding and fail-fast Spliterator
over the elements in this set

import java.util.*;
class TestCollection9{
public static void main(String args[]){
//Creating HashSet and adding elements
HashSet<String> set=new HashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//Traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Java LinkedHashSet class

Java LinkedHashSet class is a Hash table and Linked list implementation of the set interface.
It inherits HashSet class and implements Set interface.

The important points about Java LinkedHashSet class are:


 Contains unique elements only like HashSet.
 Provides all optional set operations, and permits null elements.
 Maintains insertion order.

Hierarchy of LinkedHashSet class


The LinkedHashSet class extends HashSet class which implements Set interface. The Set
interface inherits Collection and Iterable interfaces in hierarchical order.

LinkedHashSet class declaration


Let's see the declaration for java.util.LinkedHashSet class.
1. public class LinkedHashSet<E> extends HashSet<E> implements Set<E>, Cloneable,
Serializable

Constructors of Java LinkedHashSet class


Constructor Description
HashSet() It is used to construct a default HashSet.
HashSet(Collection c) It is used to initialize the hash set by using the elements of
the collection c.
LinkedHashSet(int capacity) It is used initialize the capacity of the linkedhashset to the
given integer value capacity
LinkedHashSet(int capacity, It is used to initialize both the capacity and the fill ratio
float fillRatio) (also called load capacity) of the hash set from its argument.
Example of LinkedHashSet class:
import java.util.*;
class TestCollection10{
public static void main(String args[]){
LinkedHashSet<String> al=new LinkedHashSet<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}

Java TreeSet class

Java TreeSet class implements the Set interface that uses a tree for storage. It inherits
AbstractSet class and implements NavigableSet interface. The objects of TreeSet class are
stored in ascending order.
The important points about Java TreeSet class are:
 Contains unique elements only like HashSet.
 Access and retrieval times are quiet fast.
 Maintains ascending order.

Hierarchy of TreeSet class


As shown in above diagram, Java TreeSet class implements NavigableSet interface. The
NavigableSet interface extends SortedSet, Set, Collection and Iterable interfaces in
hierarchical order.
TreeSet class declaration
Let's see the declaration for java.util.TreeSet class.
1. public class TreeSet<E> extends AbstractSet<E> implements NavigableSet<E>,
Cloneable,Serializable

Constructors of Java TreeSet class


Constructor Description
TreeSet() It is used to construct an empty tree set that will be sorted in an
ascending order according to the natural order of the tree set.
TreeSet(Collection c) It is used to build a new tree set that contains the elements of the
collection c.
TreeSet(Comparator It is used to construct an empty tree set that will be sorted according
comp) to given comparator.
TreeSet(SortedSet ss) It is used to build a TreeSet that contains the elements of the given
SortedSet.

Methods of Java TreeSet class


Methods Description
Boolean addAll(Collection c) It is used to add of the elements in the specified collection
to this set.
Boolean contains(Object o) It is used to return true if this set contains the specified
element.
Boolean isEmpty() It is used to return true if this set contains no elements.

Java TreeSet Example


Import java.util.*;
Class TestCollection11{
Public static void main(String args[]){
//Creating and adding elements
TreeSet<String> al = new TreeSet<String>();
al.add(“Ravi”);
al.add(“Vijay”);
al.add(“Ravi”);
al.add(“Ajay”);
//Traversing elements
Iterator<String> itr = al.iterator();
While(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Difference between HashSet and TreeSet
HashSet TreeSet
The elements in a HashSet are unordered. If The elements of a TreeSet are ordered. This
you use an iterator to visit the elements of a order is not based on the order that
HashSet, do not expect them to be returned elements are added to a TreeSet. Instead,
in the same order in which they were added. elements that are added to a TreeSet must
implement that Comparable interface; i.e.,
they must have a compareTo(Object obj)
method. The TreeSet uses this method
internally to order the elements.
A hashSet is backed by a hash table A TreeSet is backed by a balanced binary
tree.
The methods add(), remove(), contains(), and A TreeSet provides O(log n) performance for
size() offer constant time performance. In add(), remove(), and contains(). This means as
Big-Oh notation, this is O(1). This means that we add more elements, it will take longer to
the number of ele,ments in the HashSet search for, add or remove elements.
won’t affect the time to search for, add or
remove elements.

Queue;
Java Queue Interface
Java Queue interface orders the element in FIFO(First In First Out) manner. In FIFO, first
element is removed first and last element is removed at last

Queue Interface declaration


1. public interface Queue<E> extends Collection<E>

Methods of Java Queue Interface


Method Description
boolean add(object) It is used to insert the specified element into this queue and
return true upon success.
boolean offer(object) It is used to insert the specified element into this queue.
Object remove() It is used to retrieves and removes the head of this queue.
Object poll() It is used to retrieves and removes the head of this queue, or
returns null if this queue is empty.
Object element() It is used to retrieves, but does not remove, the head of this
queue.
Object peek() It is used to retrieves, but does not remove, the head of this
queue, or returns null if this queue is empty

PriorityQueue class
The PriorityQueue class provides the facility of using queue. But it does not orders the
elements in FIFO manner. It inherits AbstractQueue class.
PriorityQueue class declaration
Let's see the declaration for java.util.PriorityQueue class.
1. public class PriorityQueue<E> extends AbstractQueue<E> implements Serializable

Java PriorityQueue Example


import java.util.*;
class TestCollection12{
public static void main(String args[]){
PriorityQueue<String> queue=new PriorityQueue<String>();
queue.add("Amit");
queue.add("Vijay");
queue.add("Karan");
queue.add("Jai");
queue.add("Rahul");
System.out.println("head:"+queue.element());
System.out.println("head:"+queue.peek());
System.out.println("iterating the queue elements:");
Iterator itr=queue.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
queue.remove();
queue.poll();
System.out.println("after removing two elements:");
Iterator<String> itr2=queue.iterator();
while(itr2.hasNext()){
System.out.println(itr2.next());
}
}
}

Java Deque Interface


Java Deque Interface is a linear collection that supports element insertion and removal at both
ends. Deque is an acronym for "double ended queue".

Deque Interface declaration


1. public interface Deque<E> extends Queue<E>

Methods of Java Deque Interface


Method Description
boolean add(object) It is used to insert the specified element into this queue and
return true upon success.
boolean offer(object) It is used to insert the specified element into this queue.
Object remove() It is used to retrieves and removes the head of this queue.
Object poll() It is used to retrieves and removes the head of this queue, or
returns null if this queue is empty.
Object element() It is used to retrieves, but does not remove, the head of this
queue.
Object peek() It is used to retrieves, but does not remove, the head of this
queue, or returns null if this queue is empty

ArrayDeque class

The ArrayDeque class provides the facility of using deque and resizable-array. It inherits
AbstractCollection class and implements the Deque interface.

The important points about ArrayDeque class are:


 Unlike Queue, we can add or remove elements from both sides.
 Null elements are not allowed in the ArrayDeque.
 ArrayDeque is not thread safe, in the absence of external synchronization.
 ArrayDeque has no capacity restrictions.
 ArrayDeque is faster than LinkedList and Stack

ArrayDeque class declaration


Let's see the declaration for java.util.ArrayDeque class.
1. public class ArrayDeque<E> extends AbstractCollection<E> implements Deque<E>,
Cloneable, Serializable

Java ArrayDeque Example


import java.util.*;
public class ArrayDequeExample {
public static void main(String[] args) {
//Creating Deque and adding elements
Deque<String> deque = new ArrayDeque<String>();
deque.add("Ravi");
deque.add("Vijay");
deque.add("Ajay");
//Traversing elements
for (String str : deque) {
System.out.println(str);
}
}
}

Java ArrayDeque Example: offerFirst() and pollLast()


import java.util.*;
public class DequeExample {
public static void main(String[] args) {
Deque<String> deque=new ArrayDeque<String>();
deque.offer("arvind");
deque.offer("vimal");
deque.add("mukul");
deque.offerFirst("jai");
System.out.println("After offerFirst Traversal...");
for(String s:deque){
System.out.println(s);
}
//deque.poll();
//deque.pollFirst();//it is same as poll()
deque.pollLast();
System.out.println("After pollLast() Traversal...");
for(String s:deque){
System.out.println(s);
}
}
}

Maps - HashMap, TreeMap, LinkedHashMap;


A map contains values on the basis of key i.e. key and value pair. Each key and value pair is
known as an entry. Map contains only unique keys.

Map is useful if you have to search, update or delete elements on the basis of key.

There are two interfaces for implementing Map in java: Map and SortedMap, and three
classes: HashMap, LinkedHashMap and TreeMap. The hierarchy of Java Map is given
below:
Map doesn't allow duplicate keys, but you can have duplicate values. HashMap and
LinkedHashMap allows null keys and values but TreeMap doesn't allow any null key or
value.

Map can't be traversed so you need to convert it into Set using keySet() or entrySet() method.

Class Description
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.

Useful methods of Map interface


Method Description
Object put(Object key, Object value) It is used to insert an entry in this map
void putAll(Map map) It is used to insert the specified map in this map.
Object remove(Object key) It is used to delete an entry for the specified key.
Object get(Object key) It is used to return the value for the specified key.
boolean containsKey(Object key) It is used to search the specified key from his map.
Set keySet() It is used to return the Set view containing all the
keys.
Set entrySet() It is used to return the Set view containing all the
keys and values.

Map.Entry Interface
Entry is the sub interface of Map. So, we will be accessed it by Map. Entry name. It provides
methods to get key and value.

Methods of Map.Entry interface


Method Description
Object getKey() It is used to obtain key.
Object getValue() It is used to obtain value
Java Map Example: Generic (New Style)
import java.util.*;
class MapInterfaceExample{
public static void main(String args[]){
Map<Integer,String> map=new HashMap<Integer,String>();
map.put(100,"Amit");
map.put(101,"Vijay");
map.put(102,"Rahul");
for(Map.Entry m:map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}

Java HashMap class

Java HashMap class implements the map interface by using a hashtable. It inherits
AbstractMap class and implements Map interface.

The important points about Java HashMap class are:


 A HashMap contains values based on the key.
 It contains only unique elements.
 It may have one null key and multiple null values.
 It maintains no order.

Hierarchy of HashMap class


As shown in the above figure, HashMap class extends AbstractMap class and implements
Map interface.

HashMap class declaration


Let's see the declaration for java.util.HashMap class.
1. public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>,
Cloneable, Serializable
HashMap class Parameters
Let's see the Parameters for java.util.HashMap class.
 K: It is the type of keys maintained by this map.
 V: It is the type of mapped values.

Constructors of Java HashMap class


Constructor Description
HashMap() It is used to construct a default HashMap
HashMap(Map m) It is used to initializes the hash map by using the elements of the
given Map object m.
HashMap(int capacity) It is used to initializes the capacity of the hash map to the given
integer value, capacity.
HashMap(int capacity, It is used to initialize both the capacity and fill ratio of the hash
float fillRatio) map by using its arguments.

Methods of Java HashMap class


Methods Description
void clear() It is used to remove all of the mappings from this map.
boolean containsKey(Object key) It is used to return true if this map contains a mapping
for the specified key.
boolean containsValue(Object It is used to return true if this map maps one or more
value) keys to the specified value.
boolean isEmpty() It is used to return true if this map contains no key-
value mappings.
Object clone() It is used to return a shallow copy of this HashMap
instance: the keys and values themselves are not
cloned.
Set entrySet() It is used to return a collection view of the mappings
contained in this map
Set keySet() It is used to return a set view of the keys contained in
this map.
Object put(Object key, Object It is used to associate the specified value with the
value) specified key in this map
int size() It is used to return the number of key-value mappings
in this map.
Collection values() It is used to return a collection view of the values
contained in this map.

Java HashMap Example


import java.util.*;
class TestCollection13{
public static void main(String args[]){
HashMap<Integer,String> hm=new HashMap<Integer,String>();
hm.put(100,"Amit");
hm.put(101,"Vijay");
hm.put(102,"Rahul");
for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}

Java HashMap Example: remove()


import java.util.*;
public class HashMapExample {
public static void main(String args[]) {
// create and populate hash map
HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put(101,"Let us C");
map.put(102, "Operating System");
map.put(103, "Data Communication and Networking");
System.out.println("Values before remove: "+ map);
// Remove value for key 102
map.remove(102);
System.out.println("Values after remove: "+ map);
}
}

Difference between HashSet and HashMap


Parameter HashMap HashSet
This is core difference among them, HashSet implement Set interface
Interface
HahMap implements Map interface
It stores data in a form of keyvalue It uses add (value) method for
Method for
pair. So it uses put(key, value) method storing data
storing data
for storing data
HashMap allows duplicate value but HashSet doesnot allow duplicate
Duplicates
not duplicate keys values
It is faster than hashset as values are It is slower than HashMap
Performance
stored with unique keys
In Hash code values is calculated In this, hash code is caluculated
using key object on the basis of value object. Hash
code can be same for two value
HashCode
object so we have to implement
Calculation
equals() method. If equals()
method return false then two
objects are different.
Java TreeMap class

Java TreeMap class implements the Map interface by using a tree. It provides an efficient
means of storing key/value pairs in sorted order.

The important points about Java TreeMap class are:


 A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
 It contains only unique elements.
 It cannot have null key but can have multiple null values.
 It is same as HashMap instead maintains ascending order.

TreeMap class declaration


Let's see the declaration for java.util.TreeMap class.
1. public class TreeMap<K,V> extends AbstractMap<K,V> implements
NavigableMap<K,V>, Cloneable, Serializable

TreeMap class Parameters


Let's see the Parameters for java.util.TreeMap class.
 K: It is the type of keys maintained by this map.
 V: It is the type of mapped values.
Constructors of Java TreeMap class
Constructor Description
TreeMap() It is used to construct an empty tree map that will be sorted
using the natural order of its key.
TreeMap(Comparator comp) It is used to construct an empty tree-based map that will
be sorted using the comparator comp.
TreeMap(Map m) It is used to initialize a tree map with the entries from m,
which will be sorted using the natural order of the keys.
TreeMap(SortedMap sm) It is used to initialize a tree map with the entries from the
SortedMap sm, which will be sorted in the same order as sm.
Methods of Java TreeMap class
Method Description
boolean containsKey(Object key) It is used to return true if this map contains a
mapping for the specified key.
boolean containsValue(Object value) It is used to return true if this map maps one or
more keys to the specified value.
Object firstKey() It is used to return the first (lowest) key currently in
this sorted map.
Object get(Object key) It is used to return the value to which this map maps
the specified key.
Object lastKey() It is used to return the last (highest) key currently in
this sorted map.
Object remove(Object key) It is used to remove the mapping for this key from
this TreeMap if present.
void putAll(Map map) It is used to copy all of the mappings from the
specified map to this map.
Set entrySet() It is used to return a set view of the mappings
contained in this map.
int size() It is used to return the number of key-value
mappings in this map.
Collection values() It is used to return a collection view of the values
contained in this map.

Java TreeMap Example:


import java.util.*;
class TestCollection15{
public static void main(String args[]){
TreeMap<Integer,String> hm=new TreeMap<Integer,String>();
hm.put(100,"Amit");
hm.put(102,"Ravi");
hm.put(101,"Vijay");
hm.put(103,"Rahul");
for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}

Java TreeMap Example: remove()

import java.util.*;
public class TreeMapExample {
public static void main(String args[]) {
// Create and populate tree map
Map<Integer, String> map = new TreeMap<Integer, String>();
map.put(102,"Let us C");
map.put(103, "Operating System");
map.put(101, "Data Communication and Networking");
System.out.println("Values before remove: "+ map);
// Remove value for key 102
map.remove(102);
System.out.println("Values after remove: "+ map);
}
}

Difference between HashMap, Linked HashMap & TreeMap


HashMap LinkedHashMap TreeMap
HashMap is LinkedHashMap is hash TreeMap is
implemented as a hash table and linked list implemented based
Implementation
table implementation of the on red-black tree
map interface structrure
HashMap won’t LinkedHashMap TreeMap is ordered
maintain ordering on mainitans insertion by the key.
Ordering keys or values order of keys, oreder in
which keys are inserted
in to LinkedHashMap
HashMap allows null LinkedHashMap allows TreeMap won’t allow
keys/values. Allows one null keys/values. Allows null keys and allows
Null keys/Values
null key and many null one null key and many many null values.
values null values
A HashMap has a better LinkedHashMap has TreeMap has less
performance than a less performance than performance than
LinkedHashMap and HashMap and more HashMap and
TreeMap performance than LinkedHashMap.
TreeMap.
A TreeMap has a less
Performance A linkedHashMap has a performace because
less performance than TreeMap arrange the
a HashMap because keys in natural
Linked HashMap needs sorting order.
the expense of
maintaining the
doubly-linked list.
Iterable, Iterator

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

There are only three methods in the Iterator interface. They are:
Method Description
public boolean It returns true if the iterator has more elements otherwise it returns
hasNext() false.
public Object next() It returns the element and moves the cursor pointer to the next
element.
public void remove() It removes the last elements returned by the iterator. It is less used.

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

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


1. Iterator<T> iterator()
which returns the iterator over the elements of type T.

Iterable Iterator
Iterable is an interface Iterator is an interface
Belongs to java.lang.package Belongs to java.util package
Provides one single abstract method called Provides tow abstract methods called
iterator() hasNext() and next()
It is a representatation of a series of elements It represents the object with iteration state.
that can be traversed

You might also like