What Is Data Structure in Java Example?
Data structures are an essential part of computer programming. They are used to store and organize data in a way that allows for efficient access and manipulation. In Java, there are several built-in data structures that you can use, such as arrays, lists, sets, and maps.
Arrays
An array is a fixed-size collection of elements of the same type. It is one of the simplest and most commonly used data structures in Java. You can access elements in an array using their index, which starts at 0.
Here’s an example:
int[] numbers = {1, 2, 3, 4, 5};
System.out.println(numbers[0]); // Output: 1
Lists
A list is an ordered collection of elements that allows duplicates. Unlike arrays, lists in Java have a dynamic size that can grow or shrink as needed. The ArrayList class is a commonly used implementation of the List interface.
import java.util.ArrayList;
import java.List;
List fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
System.println(fruits.get(1)); // Output: Banana
Sets
A set is a collection of unique elements with no defined order. The HashSet class is one implementation of the Set interface in Java.HashSet;
import java.Set;
Set
countries.add(“USA”);
countries.add(“Canada”);
countries.add(“Mexico”);
System.println(countries.contains(“Canada”)); // Output: true
Maps
A map is a collection of key-value pairs. Each key is unique, and it is used to retrieve the associated value. The HashMap class is a commonly used implementation of the Map interface in Java.HashMap;
import java.Map;
Map
population.put(“USA”, 328_200_000);
population.put(“Canada”, 37_590_000);
population.put(“Mexico”, 126_200_000);
System.println(population.get(“Canada”)); // Output: 37590000
Conclusion
Data structures are essential for efficient data storage and manipulation in Java. Arrays, lists, sets, and maps are just a few examples of the built-in data structures available. By understanding these data structures and their implementations, you can write more efficient and organized code.