0% found this document useful (0 votes)
5 views25 pages

Collections in Java

Module 5 covers Java Collections, focusing on the ArrayList class, which allows dynamic storage and manipulation of objects. It explains the differences between arrays and ArrayLists, the creation and usage of ArrayLists, and introduces generic collections for type safety. Additionally, it discusses basic operations on ArrayLists, iteration methods, and the concept of threads in Java, highlighting their importance in improving program performance.

Uploaded by

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

Collections in Java

Module 5 covers Java Collections, focusing on the ArrayList class, which allows dynamic storage and manipulation of objects. It explains the differences between arrays and ArrayLists, the creation and usage of ArrayLists, and introduces generic collections for type safety. Additionally, it discusses basic operations on ArrayLists, iteration methods, and the concept of threads in Java, highlighting their importance in improving program performance.

Uploaded by

Pushpa Kumari R
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

MODULE 5

Collections in Java

The Collection in Java is a framework that provides an architecture to store and manipulate
the group of objects.

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

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

Java ArrayList

Java ArrayList class uses a dynamic array for storing the elements. It is like an array, but
there is no size limit. We can add or remove elements anytime. So, it is much more flexible
than the traditional array. It is found in the [Link] package.

The difference between a built-in array and an ArrayList in Java, is that the size of an array
cannot be modified (if you want to add or remove elements to/from an array, you have to
create a new one).

Unlike arrays, arraylists can automatically adjust their capacity when we add or remove
elements from them. Hence, arraylists are also known as dynamic arrays.
The ArrayList in Java can have the duplicate elements also. It implements the List interface
so we can use all the methods of the List interface here. The ArrayList maintains the insertion
order internally.

It inherits the AbstractList class and implements List interface

.The important points about the Java ArrayList class are:Fullscreen


o Java ArrayList class can contain duplicate elements.
o Java ArrayList class maintains insertion order.
o Java ArrayList class is non synchronized .
o Java ArrayList allows random access because the array works on an index basis.
o In ArrayList, manipulation is a little bit slower than the LinkedList in Java because a
lot of shifting needs to occur if any element is removed from the array list.

We can not create an array list of the primitive types, such as int, float, char, etc. It is required

to use the required wrapper class in such cases. Eg, Integer,Character,Stringetc….


Differences between array and ArrayList:

Basis Array ArrayList

Definition An array is a dynamically- The ArrayList is a


created object. It serves as class of
a container that holds the Java Collections fram
constant number of values ework. It contains
of the same type. It has a popular classes
contiguous memory like Vector,
location. HashTable,
and HashMap.

Static/ Array is static in size. ArrayList


Dynamic is dynamic in size.

Resizable An array is a fixed- ArrayList is a variable-


length data structure. length data structure.
It can be resized itself
when needed.

Initializati It is mandatory to provide We can create an


on the size of an array while instance of ArrayList
initializing it directly or without specifying its
indirectly. size. Java creates
ArrayList of default
size.

Performa It performs fast in ArrayList is internally


nce comparison to ArrayList backed by the array in
because of fixed size. Java. The resize
operation in ArrayList
slows down the
performance.

Primitive/ An array can store We cannot


Generic both objects and primitive store primitive type in
type s type. ArrayList. It
automatically converts
primitive type to
object.

Iterating We use for loop or for We use an iterator to


Values each loop to iterate over an iterate over ArrayList.
array.

Type- We cannot use generics ArrayList allows us to


Safety along with array because it store
is not a convertible type of only generic/ type,
array. that's why it is type-
safe.

Length Array provides ArrayList provides


a length variable which the size() method to
denotes the length of an determine the size of
array. ArrayList.

Adding We can add elements in an Java provides


Elements array by using the add() method to
the assignment operator. add elements in the
ArrayList.

Single/ Array can be multi- ArrayList is


Multi- dimensional. always single-
Dimensio dimensional.
nal

Creating an ArrayList

Before using ArrayList, we need to import the [Link] package first. Here is how
we can create arraylists in Java:

ArrayList<Type> arrayList= new ArrayList<>();

Here, Type indicates the type of an arraylist. For example,

// create Integer type arraylist


ArrayList<Integer> arrayList = new ArrayList<>();

// create String type arraylist


ArrayList<String> arrayList = new ArrayList<>();

In the above program, we have used Integer not int. It is because we cannot use primitive
types while creating an arraylist. Instead, we have to use the corresponding wrapper classes.
Here, Integer is the corresponding wrapper class of int.
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 a collection. Now it
is type-safe, so typecasting is not required at runtime.
Let's see the old non-generic example of creating a Java collection.

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


Non - Generic Collection
When the data structure is non-generic, it causes issues when the data is tried to be

retrieved from the collection/data structure.
 Every time an element from the collection is retrieved, it needs to be explicitly type-
casted to its required type, which is a problem when there are too many elements.
The above code, when implemented using non-generic collection yields the following
output.
Example
import [Link].*;
public class Demo {
public static void main(String[] args) {
ArrayList my_list = new ArrayList();
my_list.add("Joe");
my_list.add("Rob");
my_list.add("Nate");
my_list.add("Bill");
String s1 = (String)my_list.get(0);
String s2 = (String)my_list.get(1);
String s3 = (String)my_list.get(3);
[Link](s1);
[Link](s2);
[Link](s3);
}
}
Output
:
Joe
Rob
Bill
Let's see the new generic example of creating java collection.

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


In a generic collection, we specify the type in angular braces. Now ArrayList is forced to
have the only specified type of object in it. If you try to add another type of object, it gives
a compile-time error.
Generic Collection
Errors appear at compile time than at run time.

 Code reusability: Generics help in reusing the code already written, thereby making it
usable for other types (for a method, or class, or an interface).
 If a data structure is generic, say a list, it would only take specific type of objects and
return the same specific type of object as output. This eliminates the need to typecast
individually.
 Algorithms can be implemented with ease, since they can be used to work with
different types of objects, and maintaining type safety as well as code reusability.
Example
Following is an example −
import [Link].*;
public class Demo {
public static void main(String[] args) {
ArrayList<String> my_list = new ArrayList<String>();
my_list.add("Joe");
my_list.add("Rob");
my_list.add("John");
my_list.add("Billy");
String s1 = my_list.get(0);
String s2 = my_list.get(1);
String s3 = my_list.get(3);
[Link](s1);
[Link](s2);
[Link](s3);
}
}
Output
Joe
Rob
Billy
A class named Demo contains the main function. Here, an arraylist of strings is defined.
Elements are added to this list with the help of the ‘add’ function. The ‘get’ function is used
to store the element at a specific index. The println function is used to print the specific
element on the console.

Difference between Non-generic collection and Generic Collection


Base Non-generic Collection Generic Collection

ArrayList list = new ArrayList<ReferenceType> list = new


Syntax ArrayList(); ArrayList<ReferenceType>();

Can hold any type of data. Can hold only the defined type of data.
Type-safety Hence not type-safe. Hence type safe.

Individual type casting


needs to be done at every
Typecasting retrieval. No typecasting is needed.

Compile-Time Checked for type safety at


Checking runtime. Checked for type safety at Compile-time.

Basic Operations on ArrayList

The ArrayList class provides various methods to perform different operations on array lists.
We will look at some commonly used arraylist operations in this tutorial:
 Add elements
 Access elements
 Change elements
 Remove elements
Java ArrayList Example

FileName: [Link]

Add Items

import [Link].*;
public class ArrayListExample1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
[Link]("Mango");//Adding object in arraylist
[Link]("Apple");
[Link]("Banana");
[Link]("Grapes");
//Printing the arraylist object
[Link](list);
}
}
Output:

[Mango, Apple, Banana, Grapes]


Access an Item
To access an element in the ArrayList, use the get() method and refer to the index number:

Example
[Link](0);
Change an Item
To modify an element, use the set() method and refer to the index number:

Example
[Link](0, "Orange");
Remove an Item
To remove an element, use the remove() method and refer to the index number:

Example
[Link](0);
To remove all the elements in the ArrayList, use the clear() method:

Example
[Link]();
Iterating ArrayList using Iterator

Java Iterator
An Iterator is an object that can be used to loop through collections,
like ArrayList and HashSet. It is called an "iterator" because "iterating" is the technical term
for looping.

Methods of Iterator

The Iterator interface provides 4 methods that can be used to perform various operations on
elements of collections.
 hasNext() - returns true if there exists an element in the collection
 next() - returns the next element of the collection
 remove() - removes the last element returned by the next()
 forEachRemaining() - performs the specified action for each remaining element of the
collection
Example-java program using hasNext()

import [Link].*;
public class ArrayListExample2{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
[Link]("Mango");//Adding object in arraylist
[Link]("Apple");
[Link]("Banana");
[Link]("Grapes");
//Traversing list through Iterator
Iterator itr=[Link]();//getting the Iterator
while([Link]()){//check if iterator has the elements
[Link]([Link]());//printing the element and move to next
}
}
}
Output:

Mango
Apple
Banana
Grapes
Iterating ArrayList using For-each loop

Let's see an example to traverse the ArrayList elements using the for-each loop

FileName: [Link]

import [Link].*;
public class ArrayListExample3{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
[Link]("Mango");//Adding object in arraylist
[Link]("Apple");
[Link]("Banana");
[Link]("Grapes");
//Traversing list through for-each loop
for(String fruit:list)
[Link](fruit);
}
}
Output:

Mango
Apple
Banana
Grapes
Another useful class in the [Link] package is the Collections class, which include
the sort() method for sorting lists alphabetically or numerically:

Sort an ArrayList
Example
Sort an ArrayList of Strings:

import [Link];

import [Link]; // Import the Collections class

public class Main {

public static void main(String[] args) {

ArrayList<String> cars = new ArrayList<String>();

[Link]("Volvo");

[Link]("BMW");

[Link]("Ford");

[Link]("Mazda");

[Link](cars); // Sort cars

for (String i : cars) {

[Link](i);

}
Output
BMW
Ford
Mazda
Volvo
Example
Create array list
[Link] “one”,”Two” [Link] 5 input from user [Link] element @index 5 [Link] element at
index 2 as “Three” [Link] all element using listiterator [Link] elements
import [Link].*;
public class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
ArrayList<String> ar = new ArrayList<String>();
[Link]("One");
[Link]("Two");
for(int i=0;i<5;i++)
{
String str = [Link]();
[Link](str);
}
[Link]("Element at index 5: "+[Link](5));
[Link](2,"Three");
Iterator itr = [Link]();
while([Link]())
{
[Link]([Link]()+" ");
}
[Link](ar);
[Link]("\n"+ar);
}
}Example program- for even number printing and even number multiplied by 2
import [Link].*;

public class Main


{
public static void main(String[] args)
{
Scanner sc=new Scanner([Link]);
int k=[Link]();
ArrayList<Integer> arr = new ArrayList<>();
ArrayList<Integer> arr1 = new ArrayList<>();

for (int i = 2; i <= k; i++)


{
if (i % 2 == 0)
[Link](i);
}
[Link]("List of Even Numbers:");
[Link](arr);
[Link]();
for (int i = 2; i <= k; i++)
{

if (i % 2 == 0)
[Link](i*2);
}
[Link]("List of Even Numbers multiplied by 2:");
[Link](arr1);

}
}

Example;Array rotation
import [Link].*;

public class Main


{
public static void main(String[] args)
{

Scanner sc=new Scanner([Link]);


int k=[Link]();
int l=[Link]();
ArrayList<Integer> arr = new ArrayList<>(7);
while([Link]())
{
int i=[Link]();
[Link](i);
}
[Link](arr,l);
Iterator itr=[Link]();
while([Link]())
{
[Link]([Link]()+" ");
}

}
}
What is a Thread in Java?

A thread in Java is the direction or path that is taken while a program is being executed.

Threads are mainly used to represent a software approach in order to improve the
performance of an operating system just by reducing the overhead thread that is mainly
equivalent to a classical process.

Generally, all the programs have at least one thread, known as the main thread, that is
provided by the JVM or Java Virtual Machine at the starting of the program’s execution.

At this point, when the main thread is provided, the main() method is invoked by the main
thread.

A thread is an execution thread in a program. Multiple threads of execution can be run


concurrently by an application running on the Java Virtual Machine. The priority of each
thread varies. Higher priority threads are executed before lower priority threads.

Thread is critical in the program because it enables multiple operations to take place within a
single method. Each thread in the program often has its own program counter, stack, and
local variable.

Threads allows a program to operate more efficiently by doing multiple things at the same
time.

Thread and Process are two closely related terms in multi-threading and the main difference
between Thread and Process in Java is that Threads are part of the process. i.e. one process
can spawn multiple Threads
Difference between process and thread
Process Thread

A Process simply means any program in Thread simply means a segment of a process.
execution.

The process consumes more resources Thread consumes fewer resources.

The process requires more time for Thread requires comparatively less time for
creation. creation than process.

The process is a heavyweight process Thread is known as a lightweight process

The process takes more time to terminate The thread takes less time to terminate.

Processes have independent data and A thread mainly shares the data segment, code
code segments segment, files, etc. with its peer threads.

The process takes more time for context The thread takes less time for context
switching. switching.

As each thread has its own independent resource for process execution; thus Multiple
processes can be executed parallelly by increasing the number of threads.

The given below figure shows the working of a single-threaded and a multithreaded process:

Multitasking
 In this process, the users are allowed to perform multiple tasks by CPU.
 It involves CPU switching between tasks.
 The processes share separate memory locations.
 It involves multiprocessing.
 The CPU is provided to execute many tasks at a time.
 The processes don’t share the same resources.
 Every process is assigned its own resources.
 It is slow in comparison to multithreading.
 The process of termination takes more time.

Multithreading

 Multiple threads are created from a process.


 Due to this, the power of computer is increased.
 It involves CPU switching between the threads.
 The processes are allocated same memory.
 It doesn’t involve multiprocessing.
 The CPU is provided so that multiple threads can be executed at a specific time.
 Every process shares the same set of resources with each other.
 It is fast.
 The process of thread termination takes less time.
BASIS FOR
MULTITASKING MULTITHREADING
COMPARISON

Basic Multitasking let CPU to execute Multithreading let CPU to execute

multiple tasks at the same time. multiple threads of a process

simultaneously.

Switching In multitasking CPU switches In multithreading CPU switches between

between programs frequently. the threads frequently.

Memory and In multitasking system has to In multithreading system has to allocate

Resource allocate separate memory and memory to a process, multiple threads of

resources to each program that that process shares the same memory and

CPU is executing. resources allocated to the process.

Creating a thread in Java


To implement multithreading, Java defines two ways by which a thread can be created.

 By implementing the Runnable interface.


 By extending the Thread class.

Implementing the Runnable Interface

The easiest way to create a thread is to create a class that implements the runnable interface.
After implementing runnable interface, the class needs to implement the run() method.

Run Method Syntax:


public void run()

 It introduces a concurrent thread into your program. This thread will end when run()
method terminates.
 You must specify the code that your thread will execute inside run() method.
 run() method can call other methods, can use other classes and declare variables just like
any other normal method.

class MyThread implements Runnable


{
public void run()
{
[Link]("concurrent thread started running..");
}
}

class MyThreadDemo
{
public static void main(String args[])
{
MyThread mt = new MyThread();
Thread t = new Thread(mt);
[Link]();
}
}

Output

concurrent thread started running..

To call the run()method, start() method is used. On calling start(), a new stack is provided
to the thread and run() method is called to introduce the new thread into the program.

Note: If you are implementing Runnable interface in your class, then you need to explicitly
create a Thread class object and need to pass the Runnable interface implemented class object
as a parameter in its constructor.

Extending Thread class

This is another way to create a thread by a new class that extends Thread class and create an
instance of that class. The extending class must override run() method which is the entry
point of new thread.

class MyThread extends Thread


{
public void run()
{
[Link]("concurrent thread started running..");
}
}

classMyThreadDemo
{
public static void main(String args[])
{
MyThread mt = new MyThread();
[Link]();
}
}
Output

concurrent thread started running..


In this case also, we must override the run() and then use the start() method to run the
thread. Also, when you create MyThread class object, Thread class constructor will also be
invoked, as it is the super class, hence MyThread class object acts as Thread class object.

What if we call run() method directly without using start() method?

In above program if we directly call run() method, without using start() method,

public static void main(String args[])


{
MyThread mt = new MyThread();
[Link]();
}

Doing so, the thread won't be allocated a new call stack, and it will start running in the
current call stack, that is the call stack of the main thread. Hence Multithreading won't be
there.

Can we Start a thread twice?

No, a thread cannot be started twice. If you try to do so, IllegalThreadStateException will
be thrown.

public static void main(String args[])


{
MyThread mt = new MyThread();
[Link]();
[Link](); //Exception thrown
}

When a thread is in running state, and you try to start it again, or any method try to invoke
that thread again using start() method, exception is thrown.
Thread life cycle in java
Thread life cycle:

1. New.
2. Runnable.
3. Running.
4. Blocked(Non-Runnable).
5. Dead.

Diagram:

1. New: A new thread is created but not working. A thread after creation and before
invocation of start() method will be in new state.

2. Runnable: A thread after invocation of start() method will be in runnable state. A thread in
runnable state will be available for thread scheduler.

3. Running: A thread in execution after thread scheduler select it, it will be in running state.

4. Blocked: A thread which is alive but not in runnable or running state will be in blocked
state. A thread can be in blocked state because of suspend(), sleep(), wait() methods or
implicitly by JVM to perform I/O operations.

5. Dead: A thread after exiting from run() method will be in dead state. We can use stop()
method to forcefully killed a thread.

Daemon thread in java


Daemon thread:

Daemon threads are low priority threads which are act as a service provider for user threads.
Life of a daemon thread is depends upon the user threads. JVM automatically terminates
daemon thread when all user threads are died. Daemon threads are used for background
supporting tasks.

Daemon threads are useful for background supporting tasks such as garbage collection,
releasing memory of unused objects and removing unwanted entries from the cache. Most of
the JVM threads are daemon threads.
Methods used for daemon threads:

1. public final void setDaemon(boolean on)

Marks this thread as daemon thread if on is true.

2. public final boolean isDaemon()

Returns true if thread is daemon.

Example:

[Link]

/**
* This program is used to show daemon thread example.
* @author w3spoint
*/
class Test extends Thread{
public void run(){
[Link]([Link]().getName() + " "
+ [Link]().isDaemon());
}
}

public class DaemonThreadExample1 {


public static void main(String args[]){
//creating thread.
Test thrd1 = new Test();
Test thrd2 = new Test();

//set names
[Link]("My Thread1");
[Link]("My Thread2");

//set thrd1 as daemon thread.


[Link](true);

//start threads.
[Link]();
[Link]();
}
}
Output:
My Thread1 true
My Thread2 false
Example: After starting a thread it can’t be set as daemon thread.

[Link]

/**
* This program is used to show that after starting a thread
* it can't be set as daemon thread.
* @author w3spoint
*/
class Test extends Thread{
public void run(){
[Link]([Link]().getName() + " "
+ [Link]().isDaemon());
}
}

public class DaemonThreadExample2 {


public static void main(String args[]){
//creating thread.
Test thrd1 = new Test();
Test thrd2 = new Test();

//set names
[Link]("My Thread1");
[Link]("My Thread2");

//start thrd1.
[Link]();

//set thrd1 as daemon thread.


//[Link] here.
[Link](true);

//start thread2.
[Link]();
}
}
Output:
Exception in thread "main" My Thread1 false
[Link]
at [Link](Unknown Source)
at [Link]
([Link])

Synchronization in java
Synchronization:

Synchronization is a process of controlling mutual exclusive problem in multithreading


environment. Only one thread can access a resource at a particular instance of time. When a
thread accesses a synchronized block or method, it acquires a lock on it and release the lock
either after completion of method/block or any exception occur.

1. Synchronization in java is not needed in case of immutable objects.


2. Synchronized keyword is used for performing synchronization in java.
3. Variables can’t be synchronized in java. It will give compile time error.

How to implement Synchronization:

1. Using synchronized method.


1. a. Using non-static synchronized method.
2. b. static synchronized method.
2. Using synchronized block.

Synchronized method in java


Synchronized method:

A method declared with synchronized keyword is known as synchronized method. A


synchronized method can be static or non-static.

Example: multithreading example without synchronization.

[Link]

/**
* This program is used to show the multithreading
* example without synchronization.
* @author w3spoint
*/
class PrintTable{
//not-synchronized method.
public void printTable(int n){
[Link]("Table of " + n);
for(int i=1;i<=10;i++){
[Link](n*i);
try{
[Link](500);
}catch(Exception e){
[Link](e);
}
}
}
}

class MyThread1 extends Thread{


PrintTable pt;
MyThread1(PrintTable pt){
[Link]=pt;
}
public void run(){
[Link](2);
}
}
class MyThread2 extends Thread{
PrintTable pt;
MyThread2(PrintTable pt){
[Link]=pt;
}
public void run(){
[Link](5);
}
}

public class MultiThreadExample{


public static void main(String args[]){
//creating PrintTable object.
PrintTable obj = new PrintTable();

//creating threads.
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);

//start threads.
[Link]();
[Link]();
}
}
Output:
Table of 5
Table of 2
2
5
4
10
6
15
8
20
10
25
12
30
14
35
16
40
18
45
50
20
Example: Non-static synchronized method.

[Link]

Java Inner Classes (Nested Classes)


Java inner class or nested class is a class that is declared inside the
class or interface.
We use inner classes to logically group classes and interfaces in one place
to be more readable and maintainable.

Additionally, it can access all the members of the outer class, including
private data members and methods.

Syntax of Inner class


class Java_Outer_class{
//code
class Java_Inner_class{
//code
}
}

Advantage of Java inner classes


There are three advantages of inner classes in Java. They are as follows:

1. Nested classes represent a particular type of relationship that is it


can access all the members (data members and methods) of
the outer class, including private.
2. Nested classes are used to develop more readable and
maintainable code because it logically group classes and
interfaces in one place only.
3. Code Optimization: It requires less code to write.

Need of Java Inner class


If all the class objects are a part of the outer object then it is easier to nest that
class inside the outer class. That way all the outer class can access all the
objects of the inner class.

Types of Nested classes


There are two types of nested classes non-static and static nested classes.
The non-static nested classes are also known as inner classes.

o Non-static nested class (inner class)

1. Member inner class


2. Anonymous inner class
3. Local inner class
o Static nested class

Type Description

Member Inner A class created within class and outside method.


Class

Anonymous A class created for implementing an interface or


Inner Class extending class. The java compiler decides its
name.

Local Inner A class was created within the method.


Class

Static Nested A static class was created within the class.


Class

Nested An interface created within class or interface.


Interface

Java Member Inner class


A non-static class that is created inside a class but outside a method is
called member inner class. It is also known as a regular inner class. It
can be declared with access modifiers like public, default, private, and
protected.

Syntax:

class Outer{
//code
class Inner{
//code
}
}

Java Member Inner Class Example


In this example, we are creating a msg() method in the member inner
class that is accessing the private data member of the outer class.

class TestMemberOuter1{
private int data=30;
class Inner{
void msg(){[Link]("data is "+data);}
}
public static void main(String args[]){
TestMemberOuter1 obj=new TestMemberOuter1();
[Link] in=[Link] Inner();
[Link]();
}
}
Output:
data is 30

You might also like