0% found this document useful (0 votes)
9 views41 pages

Oop Chapter - Six (1) - 1

Uploaded by

umabrish72
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)
9 views41 pages

Oop Chapter - Six (1) - 1

Uploaded by

umabrish72
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/ 41

Chapter- Six

Data Structures in Java


BY:
Andargie Mekonnen
Java data structure
Java data structure refers to a way of organizing and storing data in a
computer so that it can be accessed and modified efficiently.

Data structures are essential for managing and processing large amounts of
data, allowing you to store, retrieve, and manipulate it effectively.

Java provides various built-in data structures, including arrays, linked lists,
sets, stacks, queues, trees, and hash maps.

Each data structure is designed to handle different types of data and


operations, depending on the requirements of the application.
12/5/2024 Andargie Mekonnen 2
Arrays
An array is a basic and often used data structure in the context of Java's data structures.

It offers a method of storing a fixed-size collection of identical-type components.

Because they provide quick and easy access to elements depending on their index, arrays
are a crucial tool for managing and organizing data.

12/5/2024 Andargie Mekonnen 3


Arrays
Advantages
Data Organization: Arrays provide a structured way to store and organize elements,
improving data management.

Random Access: Elements can be accessed directly using their index, allowing for efficient
retrieval and modification.

Fixed Size: Arrays have a predetermined size, enabling efficient memory allocation.

Homogeneous Elements: Arrays store elements of the same type, ensuring data
consistency and simplifying operations.

12/5/2024 Andargie Mekonnen 4


Arrays
Advantages
Iteration: Arrays support easy iteration through elements, facilitating traversal and
processing.

Sorting and Searching: Arrays work well with sorting and searching algorithms, offering
efficient operations.

Memory Efficiency: Arrays optimize memory usage by storing elements in contiguous


regions.

Compatibility: Arrays are widely supported in Java, making them compatible with various
frameworks and tools.
12/5/2024 Andargie Mekonnen 5
Arrays
Disadvantages
Fixed Size: Arrays cannot be dynamically resized, requiring recreation for size changes.

Memory Wastage: Unused elements in larger arrays can lead to memory wastage.

Insertion and Deletion Overhead: Inserting or deleting elements in the middle of an array
requires shifting subsequent elements, resulting in inefficiency.

Lack of Flexibility: Arrays have rigid data types and cannot accommodate different data
kinds without additional arrays or data structures.

12/5/2024 Andargie Mekonnen 6


Arrays
Functions

Creating an Array: Declare and initialize an array with a specific size using the array type
and the new keyword. Syntax: datatype[] arrayName=new Datatype[size];

Accessing Elements: Use the index to access individual elements in the array.
ArrayName[Index];

Modifying Elements: Update the value of an element by assigning a new value to a specific
index in the array. ArrayName[Index]=value;

Finding Length: Use the length attribute to determine the array's length.

Iterating through the Array: Use loops to go through each element in the array and execute
12/5/2024 Andargie Mekonnen 7
Arrays
public class ArrayExample {
public static void main(String[] args) {
// Declare and initialize an array
int[] numbers = {10, 20, 30, 40, 50};

// Access elements by index


System.out.println("First element: " + numbers[0]);

// Iterate through the array


System.out.println("Array elements:");
for (int num : numbers) {
System.out.println(num);
}
}
}
12/5/2024 Andargie Mekonnen 8
Arrays
i import java.util.*;
int sum=0;
for (int i=0;i<numbers.length;i++)
{
public class ArrayExample
sum+=numbers[i];
{
}
public static void main(String[] args)
System.out.println("Sum of array
{
elements:"+sum);
int[] numbers={10,20,30,40,50}; //
Initialize an array of integers
numbers[2]=35; // Update an element in the array
System.out.println("Updated element at index
System.out.println("Element at
2:"+numbers[2]);
index 0:"+numbers[0]);
System.out.println("Elements in the array:");
System.out.println("Element at
for (int number:numbers)
index 2:"+numbers[2]);
{
System.out.println("Element at
System.out.println(number);
index 4:"+numbers[4]);
} } }

12/5/2024 Andargie Mekonnen 9


ArrayList
ArrayList in Java is a dynamic data structure that allows for the storage and manipulation
of elements.

It is part of the Java Collections Framework and is implemented using an array internally.

Advantages:
Dynamic Size: Unlike arrays, ArrayLists can dynamically grow or shrink in size as
elements are added or removed. It eliminates the need for manual resizing and allows
for handling varying amounts of data conveniently.

12/5/2024 Andargie Mekonnen 10


ArrayList
Easy Element Manipulation: ArrayLists offer methods to add, remove, and modify
elements at any position within the list. Its flexibility simplifies common operations such
as insertion, deletion, and updating, making element manipulation more efficient.

Random Access: ArrayLists support random Access to elements using their index,
enabling quick retrieval and modification of elements at specific positions within the list.
It facilitates efficient element access and enhances overall performance.

Compatibility with Java Collection Framework: ArrayLists implement the List interface,
making them compatible with other Collection classes in the Java Collections
Framework. Its compatibility allows for seamless integration with various algorithms and
operations provided by the framework.
12/5/2024 Andargie Mekonnen 11
ArrayList
Disadvantages:
Higher Memory Overhead: ArrayLists require additional memory to maintain their
internal structure, resulting in higher memory overhead compared to arrays. It can be a
concern when dealing with large collections of elements.

Slower Insertion and Deletion: Inserting or deleting elements in the middle of an


ArrayList requires shifting elements, which can be time-consuming for large lists. In
scenarios where frequent insertion or deletion operations are expected, other data
structures like LinkedList may offer better performance.

12/5/2024 Andargie Mekonnen 12


ArrayList
Disadvantages:
Limited Performance for Search: Searching for an element in an unsorted ArrayList
requires iterating over the elements until a match is found. It is a linear search approach
that results in slower search performance compared to data structures optimized for
searching, such as HashSet or TreeMap.

No Primitive Type Support: ArrayLists can only store objects and do not directly support
primitive data types like int or char. To store primitive types, wrapper classes like
Integer or Character need to be used, leading to potential autoboxing and unboxing
overhead.

12/5/2024 Andargie Mekonnen 13


ArrayList
Functions:
Creating an ArrayList: Declare and initialize an ArrayList using the ArrayList class
and specify the element type within the angle brackets.

Adding Elements: Use the add method to append elements at the end of the ArrayList.

Accessing Elements: Use the get technique to retrieve the price of detail at a selected
index.

Modifying Elements: Update the cost of detail at a specific index for the usage of the
set approach.

12/5/2024 Andargie Mekonnen 14


ArrayList
Functions:
Finding Size: Use the dimensions method to get the cutting-edge quantity of factors in
the ArrayList.

Removing Elements: Use the remove approach to delete a detail at a specific index or
via providing the object reference.

Iterating through the ArrayList: Use loops to iterate over each element in the ArrayList
and perform operations on them.

12/5/2024 Andargie Mekonnen 15


ArrayList Example
import java.util.*; // Calculate and print the sum of all elements in the ArrayList
public class ArrayListExample int
{ sum=numbers.stream().mapToInt(Integer::intValue).sum();
public static void main(String[] args) System.out.println("Sum of ArrayList elements:"+sum);
{ // Update an element in the ArrayList
// Create an ArrayList to store integers numbers.set(2,35);
ArrayList<Integer> numbers=new
ArrayList<>(List.of(10,20,30,40,50)); System.out.println("Updated element at index
2:"+numbers.get(2));
//Access and print elements from the
ArrayList // Iterate through the ArrayList using a for-each loop and
System.out.println("Element at index print the elements
0:"+numbers.get(0)); System.out.println("Elements in the ArrayList:");
System.out.println("Element at index for (int number:numbers) {
2:"+numbers.get(2));
System.out.println("Element at index System.out.println(number);
4:"+numbers.get(4)); } }

12/5/2024 Andargie Mekonnen 16


Linked List
A linked list is a linear data structure in which elements are stored in separate objects
called nodes. A reference link to the following node in the sequence is included in each
node's data element.

The list's final node links to null, indicating that the list has ended.

Unlike arrays, linked lists do not require contiguous memory allocation.

Each node in a linked list can be allocated independently, allowing for dynamic memory
allocation and efficient insertion and deletion operations.

12/5/2024 Andargie Mekonnen 17


Linked List
Advantages:

Dynamic Size: LinkedList can grow or shrink dynamically, making it suitable for
varying or unknown data sizes.

Efficient Insertion and Deletion: Inserting or deleting elements within a LinkedList is


efficient, as it does not require shifting elements.

No Contiguous Memory Requirement: LinkedList does not need contiguous memory
allocation, making it flexible and suitable for unpredictable memory situations.

Easy Modification: LinkedList allows easy modification of elements by changing


reference pointers, enabling efficient manipulation.
12/5/2024 Andargie Mekonnen 18
Linked List
Disadvantages:

Slower Random Access: LinkedList has slower random Access as it requires


traversing the list to access elements by index.

Increased Memory Overhead: LinkedList requires additional memory for references


and nodes, increasing memory overhead compared to arrays.

Inefficient Search: LinkedList has slower search operations, requiring sequential


iteration to find specific elements.

12/5/2024 Andargie Mekonnen 19


Linked List
Functions:
Creating a LinkedList: Declare and initialize a LinkedList using the LinkedList class.
Adding Elements: Use the add method to append elements at the end of the
LinkedList.
Accessing Elements: Use the get method to retrieve the value of an element at a
specific index.
Modifying Elements: Update the value of an element at a particular index using the
set method.
Removing Elements: Use the remove method to delete an element at a specific index
or by providing the object reference.

12/5/2024 Andargie Mekonnen 20


Linked List
import java.util.*; // Print the LinkedList // Get the first and last elements of
public class LinkedList1 System.out.println("LinkedList:"+li the LinkedList
{ nkedList1); int
public static void main(String[] // Remove an element from the firstElement=linkedList1.getFirst();
args) LinkedList int
{ linkedList1.removeFirst(); lastElement=linkedList1.getLast();
// Create a LinkedList to store integers System.out.println("LinkedList System.out.println("First
LinkedList<Integer> linkedList1 = after removing first element:"+firstElement);
new LinkedList<>(); element:"+linkedList1); System.out.println("Last
// Add elements to the LinkedList // Check if an element exists in the element:"+lastElement);
linkedList1.add(10); LinkedList // Clear the LinkedList
linkedList1.add(20); Boolean containsElement linkedList1.clear();
linkedList1.add(30); =linkedList1.contains(30); System.out.println("LinkedList
linkedList1.add(40); System.out.println("LinkedList after clearing:"+linkedList1);
linkedList1.add(50); contains element } }
30?"+containsElement);
12/5/2024 Andargie Mekonnen 21
Linked List
import java.util.LinkedList; // Print the LinkedList

public class LinkedListExample { System.out.println("LinkedList: " + names);


// Remove an element
public static void main(String[] args) {
names.remove("Bob");
// Create a LinkedList
System.out.println("After removal: " +
LinkedList<String> names = new names);
LinkedList<>(); // Iterate through the list
// Add elements for (String name : names) {

names.add("Alice"); System.out.println(name);

names.add("Bob"); }
}
names.add("Charlie");
}

12/5/2024 Andargie Mekonnen 22


Sets in Java
 A Set is a collection that does not allow duplicate elements. It models the mathematical set
abstraction and is part of the Java Collections Framework. Sets are commonly used when
you want to ensure uniqueness in a collection of elements.

Key Characteristics of Sets


No Duplicates: A Set automatically removes duplicate elements.

No Indexing: Elements in a Set are not accessed using an index.

Implementations: Java provides several implementations of the Set interface:


 HashSet: Unordered, uses hashing.

 LinkedHashSet: Maintains insertion order.

 TreeSet: Ordered based on natural ordering or a custom comparator.


12/5/2024 Andargie Mekonnen 23
Set Implementations
HashSet fruits.add("Banana");
fruits.add("Orange");
 Uses a hash table to store elements. fruits.add("Apple"); // Duplicate, will not
be added
 Does not guarantee any specific order of elements.

 Best for fast lookups. // Print the Set


System.out.println("HashSet: " + fruits);
 Example:
// Check if an element exists
import java.util.HashSet;
System.out.println("Contains 'Banana'? "
public class HashSetExample {
+ fruits.contains("Banana"));
public static void main(String[] args) {
// Remove an element
// Create a HashSet
fruits.remove("Banana");
HashSet<String> fruits = new HashSet<>();
System.out.println("After removal: " +
// Add elements
fruits);
fruits.add("Apple");
}
}
12/5/2024 Andargie Mekonnen 24
Set Implementations
LinkedHashSet
 Extends HashSet.

 Maintains the insertion order of elements.

 Example:
cities.add("New York");
import java.util.LinkedHashSet; cities.add("Los Angeles");
public class LinkedHashSetExample { cities.add("Chicago");
public static void main(String[] args) { cities.add("New York"); // Duplicate, will not be
// Create a LinkedHashSet added
LinkedHashSet<String> cities = new LinkedHashSet<>(); // Print the Set
// Add elements System.out.println("LinkedHashSet: " + cities);
}
}

12/5/2024 Andargie Mekonnen 25


Set Implementations
TreeSet
Implements the NavigableSet interface.
Stores elements in sorted (natural) order or by a custom comparator.
Does not allow null elements.
import java.util.TreeSet; // Print the Set
public class TreeSetExample { System.out.println("TreeSet (Natural Order): "
public static void main(String[] args) { + numbers);
// Create a TreeSet
TreeSet<Integer> numbers = new TreeSet<>(); // Access first and last elements
// Add elements System.out.println("First: " + numbers.first());
numbers.add(10); System.out.println("Last: " + numbers.last());
numbers.add(5); }
numbers.add(20); }
numbers.add(5); // Duplicate, will not be
added
12/5/2024 Andargie Mekonnen 26
Set Implementations

12/5/2024 Andargie Mekonnen 27


Set Implementations
EnumSet
A specialized Set for working with enums. It is highly optimized and uses bitwise
operations for efficiency.

Stores only elements of a single enum type

Does not allow null.

Fast and memory-efficient.

When working with enums and you need a set of constants.

12/5/2024 Andargie Mekonnen 28


Set Implementations
Example
import java.util.EnumSet;
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY
}
public class EnumSetExample {
public static void main(String[] args) {
EnumSet<Day> workDays = EnumSet.range(Day.MONDAY, Day.FRIDAY);
System.out.println(workDays); // Output: [MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY]
}
}

12/5/2024 Andargie Mekonnen 29


Set Implementations
CopyOnWriteArraySet
A thread-safe implementation of the Set interface. It is part of the java.util.concurrent
package and is backed by a copy-on-write array.

No duplicates.

Thread-safe (uses a copy-on-write mechanism).

Suitable for small sets with infrequent updates.

Slower for adding/removing elements due to copying overhead.

When you need a thread-safe set with minimal concurrency overhead.

12/5/2024 Andargie Mekonnen 30


Set Implementations
Example
import java.util.concurrent.CopyOnWriteArraySet;
public class CopyOnWriteArraySetExample {
public static void main(String[] args) {
CopyOnWriteArraySet<String> set = new CopyOnWriteArraySet<>();
set.add("Apple");
set.add("Banana");
set.add("Apple"); // Duplicate, ignored
System.out.println(set); // Output: [Apple, Banana]
}
}

12/5/2024 Andargie Mekonnen 31


Set Implementations

12/5/2024 Andargie Mekonnen 32


Queue in Java
A queue is a linear data structure that follows the FIFO (First In, First Out) principle, meaning
elements are added to the rear (end) and removed from the front (beginning).

It is commonly used in scenarios like task scheduling, print queues, and breadth-first search in
graphs.

FIFO Order: Elements are processed in the order they were added.

Operations:
 enqueue: Add an element to the rear of the queue.
 dequeue: Remove an element from the front of the queue.
 peek: View the front element without removing it.

No Random Access: Elements can only be accessed at the front or rear.
12/5/2024 Andargie Mekonnen 33
Java Queue Implementation
Java provides the Queue interface in the java.util package. Common implementations
include:

LinkedList: A general-purpose linked list that implements Queue.

PriorityQueue: A queue where elements are ordered based on their natural order or
a custom comparator.

ArrayDeque: A more efficient implementation for queues compared to LinkedList.

12/5/2024 Andargie Mekonnen 34


Basic Queue Example Using LinkedList
import java.util.LinkedList; System.out.println("Queue: " + queue); // Output: [Alice,
Bob, Charlie]
import java.util.Queue;
// View the front element without removing it (peek)
public class QueueExample {
System.out.println("Front element: " + queue.peek());
public static void main(String[] args) { // Output: Alice
// Create a Queue // Remove elements from the queue (dequeue)
Queue<String> queue = new LinkedList<>(); System.out.println("Removed: " + queue.poll()); //
Output: Alice
// Add elements to the queue (enqueue)
System.out.println("Queue after removal: " + queue);
queue.add("Alice"); // Output: [Bob, Charlie]
queue.add("Bob"); // Check if the queue is empty
queue.add("Charlie"); System.out.println("Is queue empty? " +
// Display the queue queue.isEmpty()); // Output: false
}}
12/5/2024 Andargie Mekonnen 35
.
Priority Queue Example
import java.util.PriorityQueue; priorityQueue.add(30);
import java.util.Queue; priorityQueue.add(10);

public class PriorityQueueExample { // Display the queue (elements are ordered by natural
order)
public static void main(String[] args) {
System.out.println("PriorityQueue: " +
// Create a PriorityQueue priorityQueue); // Output: [10, 20, 30, 40]
Queue<Integer> priorityQueue = new // Remove elements
PriorityQueue<>(); System.out.println("Removed: " +
// Add elements to the queue priorityQueue.poll()); // Output: 10

priorityQueue.add(40); System.out.println("PriorityQueue after removal: " +


priorityQueue); // Output: [20, 40, 30]
priorityQueue.add(20);
}
}

12/5/2024 Andargie Mekonnen 36


Using ArrayDeque for Queue
import java.util.ArrayDeque; // Add elements
import java.util.Queue; queue.add("Task1");
queue.add("Task2");

public class ArrayDequeExample { queue.add("Task3");

public static void main(String[] args) {


// Process elements
// Create a Queue using ArrayDeque
while (!queue.isEmpty()) {
Queue<String> queue = new
ArrayDeque<>(); System.out.println("Processing: " + queue.poll());
}
}
}

12/5/2024 Andargie Mekonnen 37


Comparison of Queue Implementations

12/5/2024 Andargie Mekonnen 38


Stack in Java
A Stack is a linear data structure that follows the LIFO (Last In, First Out) principle,
meaning the last element added to the stack is the first one to be removed.
It is commonly used for operations like reversing strings, evaluating expressions, and
function call management in recursion.
LIFO Order: Elements are added to the top of the stack and removed from the top.
Basic Operations:
 Push: Add an element to the stack.
 Pop: Remove the top element from the stack.
 Peek: View the top element without removing it.
 isEmpty: Check if the stack is empty.

12/5/2024 Andargie Mekonnen 39


Example Using the Stack Class
import java.util.Stack; // Pop elements from the stack
public class StackExample { System.out.println("Popped: " + stack.pop()); //
public static void main(String[] args) {
Output: 30
// Create a Stack
Stack<Integer> stack = new Stack<>(); System.out.println("Stack after pop: " + stack); //
// Push elements onto the stack Output: [10, 20]
stack.push(10); // Check if the stack is empty
stack.push(20); System.out.println("Is stack empty? " +
stack.push(30);
stack.isEmpty()); // Output: false
// Display the stack
System.out.println("Stack: " + stack); // Output: // Pop remaining elements
[10, 20, 30] stack.pop();
// Peek at the top element stack.pop();
System.out.println("Top element: " + // Check if the stack is empty again
stack.peek()); // Output: 30
System.out.println("Is stack empty? " +
stack.isEmpty()); // Output: true
}
}
12/5/2024 Andargie Mekonnen 40
12/5/2024 Andargie Mekonnen 41

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy