Oop Chapter - Six (1) - 1
Oop Chapter - Six (1) - 1
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.
Because they provide quick and easy access to elements depending on their index, arrays
are a crucial tool for managing and organizing data.
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.
Sorting and Searching: Arrays work well with sorting and searching algorithms, offering
efficient operations.
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.
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};
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.
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.
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.
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.
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.
The list's final node links to null, indicating that the list has ended.
Each node in a linked list can be allocated independently, allowing for dynamic memory
allocation and efficient insertion and deletion operations.
Dynamic Size: LinkedList can grow or shrink dynamically, making it suitable for
varying or unknown data sizes.
No Contiguous Memory Requirement: LinkedList does not need contiguous memory
allocation, making it flexible and suitable for unpredictable memory situations.
names.add("Alice"); System.out.println(name);
names.add("Bob"); }
}
names.add("Charlie");
}
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);
}
}
No duplicates.
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:
PriorityQueue: A queue where elements are ordered based on their natural order or
a custom comparator.
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