Data structures are fundamental concepts in computer science used to store, organize, and manipulate data efficiently. Java provides built-in classes and interfaces to implement these structures, which are essential for solving real-world problems effectively.
Arrays are fixed-size collections of elements of the same type stored sequentially in memory.
int[] numbers = {1, 2, 3, 4, 5};
System.out.println(numbers[0]); // Output: 1
A Linked List is a dynamic data structure where each element (node) contains data and a reference to the next node.
import java.util.LinkedList;
LinkedList<String> list = new LinkedList<>();
list.add("Java");
list.add("Python");
System.out.println(list); // Output: [Java, Python]
A stack is a linear data structure that follows the Last In, First Out (LIFO) principle. The most recently added element is the first to be removed. Common operations include push
(add), pop
(remove), and peek
(view top element).
import java.util.Stack;
Stack<Integer> stack = new Stack<>();
stack.push(10);
stack.push(20);
System.out.println(stack.pop()); // Output: 20
A queue is a linear data structure that follows the First In First Out (FIFO) principle. This means the element inserted first is the one removed first.
import java.util.LinkedList;
import java.util.Queue;
Queue<String> queue = new LinkedList<>();
queue.add("Task1");
queue.add("Task2");
System.out.println(queue.poll()); // Output: Task1
A Hash Map is a data structure that stores key-value pairs, allowing fast access to values based on their unique keys.
It uses a hash function to compute an index into an array of buckets, from which the desired value can be found.
import java.util.HashMap;
HashMap<String, Integer> map = new HashMap<>();
map.put("Apple", 10);
map.put("Banana", 5);
System.out.println(map.get("Apple")); // Output: 10
A tree is a hierarchical data structure made up of nodes, where each node has a value and links to child nodes.
It starts with a root node and branches out, forming a structure similar to a real tree.
class Node {
int data;
Node left, right;
Node(int item) {
data = item;
left = right = null;
}
}
class BinaryTree {
Node root;
BinaryTree() { root = null; }
}
A graph is a data structure that consists of a set of nodes (also called vertices) and a set of edges that connect pairs of nodes. Graphs are used to represent relationships or connections between objects.
import java.util.*;
class Graph {
private int V;
private LinkedList<Integer> adj[];
Graph(int v) {
V = v;
adj = new LinkedList[v];
for(int i=0; i<v; ++i)
adj[i] = new LinkedList();
}
void addEdge(int v, int w) {
adj[v].add(w);
}
}
Understanding fundamental data structures is essential for efficient problem-solving in computer science.
Mastering these structures builds a strong foundation for algorithms, system design, and real-world applications.