16
NovWhat is Data Structure in Java & Classification (Tutorial)
What is Java?
Isn't Java the language being taught to you after C/C++? Have you ever thought why so? Java is a high-level versatile programming language whose rules and syntax are based on C and C++ languages. It is used to develop mobile applications, desktop applications, web applications, web servers, and servers. Thus, it's a widely used object-oriented programming language and software platform that runs on computers, mobile devices, gaming consoles, etc.
In this Java tutorial, we'll look at the building blocks of any programming language i.e. data structures. We'll study various types of data structures in Java with illustrations. If you're a beginner to Java, you must understand the data structures the language supports. So let's begin.
Become a full stack expert with our Java Full Stack Developer Course Training—enroll and build your future!
Read More: Top 50 Java Interview Questions and Answers |
What are Data Structures in Java?
A data structure is the method of storing and organizing data in the computer memory. It is the branch of Computer Science that deals with arranging such large datasets in such a manner so that they can be accessed and modified as per the requirements. For example, the date is a data structure. It includes three types of data viz date (numeric value), month (character or numeric value), and year (numeric value).
Read More: What are Data Structures? |
Need for Data Structures in Java
- Processing Speed: As the data is increasing, high-speed processing is required to handle such a massive amount of data, but the processor may fail to deal with that if the data isn't organized into a data structure.
- Efficient Data Organization: Data structures provide efficient ways to organize and store data, enabling faster access, retrieval, and manipulation of information.
- Memory Management: Data structures help manage memory efficiently by allocating and deallocating memory as needed.
- Concurrency and Multithreading in Java: Java provides thread-safe data structures like ConcurrentHashMap and ConcurrentLinkedQueue for concurrent programming.
- Reusability: Data structures provide reusability of data, i.e. after implementing a particular data structure once, we can use it many times at any other place.
- Higher-Level Abstractions: Java's built-in data structures and collection framework offer higher-level abstractions like lists, sets, maps, and queues, simplifying common programming tasks.
Classification of Data Structures in Java
Data Structures in Java are mainly classified into two categories:
- Primitive Data Structures: They store the data of only one type i.e. built-in data types. Data types like byte, short,
integer
,float
,character
, andbooleans
come in this category.Read More: Data Types in Java - Non-Primitive Data Structures: They can store the data of more than one type i.e. derived data types. Data types like
arrays
,linked lists
,trees
, etc. come in this category. Non-Primitive Data Structures are data structures derived from Primitive Data Structures.Based on the structure and arrangement of data, these data structures are further divided into two categories
- Linear Data Structures: The data in this data structure is arranged in a sequence, one after the other i.e. each element appears to be connected linearly.
Based on the memory allocation, the Linear Data Structures are again classified into two types:
- Static Data Structures: They have a fixed size. The memory is allocated at the compile time, and its size cannot be changed by the user after being compiled; however, the data can be modified. e.g. array
- Dynamic Data Structures: They don't have a fixed size. The memory is allocated at the run time, and its size varies during the execution of the program. Moreover, the user can modify the size as well as the data elements stored at the run time. e.g.
linked list
,stack
,queue
- Non-Linear Data Structures: The data in this data structure are not arranged in a sequence. They form a hierarchy i.e. the data elements have multiple ways to connect to other elements. e.g.
tree
andgraph
- Linear Data Structures: The data in this data structure is arranged in a sequence, one after the other i.e. each element appears to be connected linearly.
Types of Linear Data Structures in Java
1. Arrays
An array is a data structure used to store the elements of a particular type. For example, an integer array will hold only the value of any integer, but a character array will hold the characters only. The values get stored at contagious memory locations that can be accessed with their index number.
Syntax
dataType arrayName[arraySize];
Example of Array in Java
class Array_Example
{
public static void main (String[] args)
{
// declaring integer array.
int[] arr;
arr = new int[6];
arr[0] = 10;
arr[1] = 40;
arr[2] = 50;
arr[3] = 20;
arr[4] = 60;
arr[5] = 80;
// accessing the array elements
for (int i = 0; i < arr.length; i++)
System.out.println(arr[i]);
}
}
In this example, an integer array named "arr" of size 6 is declared and initialized with predetermined values, with each element's index denoting a different integer value.
Output
10
40
50
20
60
80
Read More: |
2. ArrayList
ArrayList is a Java class implemented using the List interface. In the Java ArrayList, the size of the array is not fixed. The List interface extends the Collections framework.
Syntax
import java.util.ArrayList;
// Declare an ArrayList of a specific type
ArrayList arrayListName = new ArrayList<>();
Example of ArrayList in Java
import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
// Create an ArrayList to store strings
ArrayList names = new ArrayList<>();
// Add elements to the ArrayList
names.add("ScholarHat");
names.add("Sakshi");
names.add("Sourav");
// Print the elements of the ArrayList
System.out.println("ArrayList elements:");
for (String name : names) {
System.out.println(name);
}
// Access elements by index
String first = names.get(0);
System.out.println("First element: " + first);
// Remove an element
names.remove("Sakshi");
// Check if an element exists
if (names.contains("Sakshi")) {
System.out.println("Sakshi is in the list.");
} else {
System.out.println("Sakshi is not in the list.");
}
// Size of the ArrayList
int size = names.size();
System.out.println("Size of the ArrayList: " + size);
}
}
Output
ArrayList elements:
ScholarHat
Sakshi
Sourav
First element: ScholarHat
Sakshi is not in the list.
Size of the ArrayList: 2
3. Linked Lists
A Linked List consists of a series of connected nodes randomly stored in the memory. Here, each node consists of two parts, the first part is the data and the second part contains the pointer to the address of the next node. It holds numerous items of the same type.
Syntax
LinkedListvar = new LinkedList();
Example of Linked Lists in Java
import java.util.*;
public class Main {
public static void main(String args[]) {
// Creating object of class Linked List
LinkedList ll = new LinkedList();
// Adding elements to linked list
ll.add("ScholarHat");
ll.add("Sakshi");
ll.add("Sourav");
ll.add("Pragati");
// Printing the linked list
System.out.println(ll);
}
}
The above code creates a LinkedList named ll, adds some elements to it, and prints the LinkedList.
Output
[ScholarHat, Sakshi, Sourav, Pragati]
Read More: Linked List in Data Structures |
4. Stack
A stack is an ordered list or a container in which insertion and deletion can be done from one end known as the top of the stack. The last inserted element is available first and is the first one to be deleted. Hence, it is known as Last In, First Out LIFO, or First In, Last Out FILO. Stacks do not have a fixed size and their size can be increased or decreased depending upon the number of elements.
Syntax
Stack var = new Stack(size);
Example of a Stack in Java
import java.util.Stack;
public class StackExample {
public static void main(String[] args) {
Stack stack = new Stack<>();
// Push elements onto the stack
stack.push(100);
stack.push(200);
stack.push(300);
// Print the top element of the stack
System.out.println("Top element:"+stack.peek());
// Pop elements from the stack
int poppedElement=stack.pop();
System.out.println("Popped element:"+poppedElement);
// Check if the stack is empty
System.out.println("Is the stack empty? "+stack.isEmpty());
// Get the size of the stack
System.out.println("Stack size:"+stack.size());
System.out.println("Stack elements:");
for (Integer element:stack)
{
System.out.println(element);
}
}
}
The above program in the Java Editor demonstrates the creation of a Stack and its associated operations.
Output
Top element:300
Popped element:300
Is the stack empty? false
Stack size:2
Stack elements:
100
200
Read More: Implementing Stack in Data Structures |
5. Queue
A queue is an ordered list in which insertion is done at one end called REAR and deletion at another end called FRONT. The first inserted element is available first for the operations to be performed and is the first one to be deleted. Hence, it is known as First In First Out, FIFO, or Last In Last Out, LILO.
Syntax
Queue q1 = new LinkedList();
Example of a Queue in Java Compiler
import java.util.LinkedList;
import java.util.Queue;
public class Main {
public static void main(String[] args) {
// Implementing Queue
Queue queue = new LinkedList<>();
// Adding Elements in queue
queue.add("Sakshi");
queue.add("Sourav");
queue.add("Jayanti");
queue.add("Pragati");
System.out.println(queue.peek());
// Removing elements from queue
queue.remove();
queue.remove();
System.out.println(queue.peek());
// Returns the total number of elements present in the queue
System.out.println(queue.size());
// Check if the queue is empty
if (queue.isEmpty()) {
System.out.println("The queue is empty");
} else {
System.out.println("The queue is not empty");
}
}
}
In the above code, we created a queue using a linked list. After that, we perform insertion, deletion, and print operations on the queue.
Output
Sakshi
Jayanti
2
The queue is not empty
Read More: Queue in Data Structures |
Types of Non-Linear Data Structures in Java
1. Graph
A graph is a collection of nodes that consist of data and are connected to other nodes of the graph. Formally a Graph is composed of a set of vertices( V ) and a set of edges( E ). The graph is denoted by G(V, E). In a graph, each entity is symbolized by a vertex, while edges denote the connections or associations between entities.
Syntax
BaseType obj = new BaseType ();
Example of Graphs in Java
class Graph {
class Edge {
int src, dst; //source and destination
}
// number of vertices and edges
int vertices, edges;
Edge[] edge;
Graph(int vertices, int edges) {
this.vertices = vertices;
this.edges = edges;
// initialize the edge array
edge = new Edge[edges];
for(int i = 0; i < edges; i++) {
edge[i] = new Edge();
}
}
public static void main(String[] args) {
// create an object of Graph class
int noVertices = 5;
int noEdges = 8;
Graph g = new Graph(noVertices, noEdges);
// create graph
g.edge[0].src = 1;
g.edge[0].dst = 2;
g.edge[1].src = 1;
g.edge[1].dst = 3;
g.edge[2].src = 1;
g.edge[2].dst = 4;
g.edge[3].src = 2;
g.edge[3].dst = 4;
g.edge[4].src = 2;
g.edge[4].dst = 5;
g.edge[5].src = 3;
g.edge[5].dst = 4;
g.edge[6].src = 3;
g.edge[6].dst = 5;
g.edge[7].src = 4;
g.edge[7].dst = 5;
for(int i = 0; i < noEdges; i++) {
System.out.println(g.edge[i].src + " - " + g.edge[i].dst);
}
}
}
The above code initializes a graph with a given number of vertices and edges, creates an array of Edge objects, and sets the source and destination vertices for each edge. Finally, it prints out the source and destination vertices for each edge in the graph.
Output
1 - 2
1 - 3
1 - 4
2 - 4
2 - 5
3 - 4
3 - 5
4 - 5
Read More: Graphs in Data Structures - Types of Graphs, Representation & Operations |
2. Tree
A tree is a collection of objects or entities known as nodes connected by edges and has a hierarchical relationship between the nodes. The topmost node of the tree is called the root node from which the tree originates, and the nodes below it are called the child nodes.
Example of Trees in Java
class Tree {
int info;
Tree left, right;
Tree(int info, Tree left, Tree right) {
this.info = info;
this.left = left;
this.right = right;
}
public String toString() {
return info + ", Left child: " + left + ", Right child: " + right;
}
public static void main(String[] args) {
Tree tree = new Tree(1,
new Tree(2, new Tree(0, null, null), new Tree(0, null, null)),
new Tree(3, new Tree(0, null, null), null));
System.out.println(tree);
}
}
The above Java code defines a Tree class with an info field representing the node value and left and right fields representing the left and right child nodes, respectively. The toString() method is overridden to provide a string representation of the tree node and its children.
Output
1, Left child: 2, Left child: 0, Left child: null, Right child: null, Right child: 0, Left child: null, Right child: null, Right child: 3, Left child: 0, Left child: null, Right child: null, Right child: null
Read More: Trees in Data Structures - Its Structure, Operations & Applications |
3. HashMap
HashMap in Java is an implementation of the Map interface that stores data as key-value pairs in a hash table. Each key must be unique having any non-null reference type, and values can be of any type, including null.
Syntax
Map hashMap = new HashMap<>();
Example of HashMap in Java
import java.util.*;
public class HashMapExample {
public static void main(String[] args) {
// Creating HashMap with String keys and Integer values
Map<String, Integer> map = new HashMap<>();
// Inserting entries in the Map
map.put("Sakshi", 100);
map.put("Sourav", 200);
map.put("Jayanti", 300);
// Iterating over Map using for-each loop
for (Map.Entry<String, Integer> entry : map.entrySet())
// Printing key-value pairs
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
In the above code, we created a HashMap named map that maps String keys to integer values. Three key-value pairs are added to the HashMap using the put method. The entrySet method iterates over the entries of the map. For each entry in the map, it prints the key-value pair using getKey and getValue methods of the Map.Entry interface.
Output
Sourav 200
Sakshi 100
Jayanti 300
Read More: Interface in Java |
4. HashSet
HashSet class in Java implements the Set interface, a collection of unique elements. It stores the elements in the hash table. HashSet does not accept duplicate values. The order of the objects in the HashSet varies based on their hash code.
Example of HashSet in Java
import java.util.HashSet;
public class HashSetExample {
public static void main(String[] args) {
// Create a HashSet to store strings
HashSet<String> hashSet = new HashSet<>();
// Adding elements to the HashSet
hashSet.add("Sakshi");
hashSet.add("Sourav");
hashSet.add("ScholarHat");
hashSet.add("Sakshi"); // Adding duplicate element, will be ignored
System.out.println("HashSet: " + hashSet);
// Check if an element exists in the HashSet
String searchElement = "ScholarHat";
if (hashSet.contains(searchElement)) {
System.out.println(searchElement + " is present in the HashSet.");
} else {
System.out.println(searchElement + " is not present in the HashSet.");
}
// Remove an element from the HashSet
hashSet.remove("Sourav");
System.out.println("After removing Sourav, HashSet: " + hashSet);
// Get the size of the HashSet
int size = hashSet.size();
System.out.println("Size of the HashSet: " + size);
}
}
The above example illustrates how HashSet handles unique elements and provides methods for checking containment and removing elements.
Output
HashSet: [Sourav, Sakshi, ScholarHat]
ScholarHat is present in the HashSet.
After removing Sourav, HashSet: [Sakshi, ScholarHat]
Size of the HashSet: 2
5. TreeMap
TreeMap class in Java implements the SortedMap interface, which extends the Map interface. It uses a Red-Black tree to store key-value pairs in sorted order based on the natural order of the keys.
Example of TreeMap in Java
import java.util.Map;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
Map<String, Integer> treeMap = new TreeMap<>();
// Adding elements to the tree map
treeMap.put("Sakshi", 1);
treeMap.put("Sourav", 3);
treeMap.put("Pragati", 2);
// Getting values from the tree map
int valueA = treeMap.get("Sakshi");
System.out.println("Value of Sakshi: " + valueA);
// Removing elements from the tree map
treeMap.remove("Sourav");
for (String key : treeMap.keySet()) {
System.out.println("Key: " + key + ", Value: " + treeMap.get(key));
}
}
}
The above example showcases TreeMap's functionality for maintaining sorted key-value pairs and performing common map operations like adding, retrieving, and removing elements.
Output
Value of Sakshi: 1
Key: Pragati, Value: 2
Key: Sakshi, Value: 1
6. TreeSet
The TreeSet class of the Collections framework in Java implements the SortedSet interface. You cannot insert duplicate values in the HashSet due to the Set interface. It uses a self-balancing binary search tree to store elements in sorted order.
Example of TreeSet in Java
import java.util.*;
class Treeset_Example {
public static void main(String[] args)
{
Set<string>> ts1 = new TreeSet<>();
// Elements are added using add() method
ts1.add("Sakshi");
ts1.add("Sourav");
ts1.add("ScholarHat");
// Duplicates
ts1.add("ScholarHat");
System.out.println(ts1);
}
}
The above code creates a TreeSet named ts1 to store String elements. Strings are added to ts1 using the add() method. The duplicate elements get ignored. Finally, the contents of ts1 having sorted unique elements are printed.
Output
[Sakshi, ScholarHat, Sourav]
Advantages of Data Structures in Java
- Efficient Data Organization: Data structures provide efficient ways to organize and manage data, allowing for quick access, insertion, deletion, and modification of data elements.
- Scalability and Flexibility: Java's rich collection of data structures allows developers to choose the most suitable structure according to their requirements.
- Code reusability: The developers do not always need to begin from scratch as they can use reusable data structures thus saving time and efficiency.
- Optimized Memory Usage: By choosing appropriate data structures, memory usage can be optimized, reducing wastage and improving overall performance.
- Abstraction and Encapsulation: Data structures encapsulate data and operations, providing a level of abstraction that simplifies programming tasks and promotes code reusability.
Choosing the Right Data Structure in Java
As a Java developer, you need to know every data structure in Java programming in complete detail. You must be careful enough while selecting the proper data structure for your project. We'll look at the approach to selecting the data structure in Java.
- Understand Requirements: Start by thoroughly understanding the requirements of your application like the type of data to be stored, the frequency and nature of data operations, memory constraints, and expected performance metrics.
- Analyze Operations: Take a proper analysis of the operations that need to be performed on the data, including searching, sorting, updating, and traversing.
- Consider Time and Space Complexity: Evaluate the time and space complexity of data operations for various data structures.
- Evaluate Built-in Data Structures: In Java, we have built-in data structures in the Collections Framework like ArrayList, LinkedList, HashMap, TreeMap, HashSet, TreeSet, etc.
- Iterative Refinement: Data structure selection is an iterative process. As your understanding of the problem evolves and new requirements emerge, you need to revisit your data structure choices and make proper adjustments.