In Java, a data structure refers to a way of organizing and storing data in a computer so that it can be accessed and manipulated efficiently. It defines the relationship between the data elements, operations that can be performed on the data, and the rules or constraints for accessing and modifying the data.
Some of the commonly used data structures include:
1.ArrayList: It is a resizable array implementation of the List interface. It allows fast random access to elements and dynamic resizing of the array.
import java.util.ArrayList;
ArrayList<Integer> list = new ArrayList<>();
list.add(10);
list.add(20);
System.out.println(list.get(0)); // Output: 10
2.LinkedList: It is a doubly-linked list implementation of the List interface. It provides fast insertion and deletion operations but slower random access.
import java.util.LinkedList;
LinkedList<String> linkedList = new LinkedList<>();
linkedList.add("Apple");
linkedList.add("Banana");
System.out.println(linkedList.getFirst()); // Output: Apple
3.HashMap: It stores key-value pairs and provides constant-time performance for the basic operations like get() and put(). It does not maintain order.
import java.util.HashMap;
HashMap<String, Integer> map = new HashMap<>();
map.put("John", 25);
map.put("Alice", 30);
System.out.println(map.get("John")); // Output: 25
4.HashSet: It is an implementation of the Set interface. It stores unique elements and does not maintain any order.
import java.util.HashSet;
HashSet<String> set = new HashSet<>();
set.add("Apple");
set.add("Banana");
System.out.println(set.contains("Apple")); // Output: true
5.Stack: It is a Last-In-First-Out (LIFO) data structure. It extends Vector with five operations that allow a vector to be treated as a stack.
import java.util.Stack;
Stack<Integer> stack = new Stack<>();
stack.push(10);
stack.push(20);
System.out.println(stack.pop()); // Output: 20
6.Queue: It is a First-In-First-Out (FIFO) data structure. LinkedList class implements this interface.
import java.util.Queue;
import java.util.LinkedList;
Queue<Integer> queue = new LinkedList<>();
queue.add(10);
queue.add(20);
System.out.println(queue.poll()); // Output: 10
These are just a few examples of the built-in data structures available in Java. Depending on your requirements, you can choose the appropriate data structure to efficiently manage your data.
Top comments (0)