1. Arrays
An array is a fixed-size data structure that stores elements of the same
type.
It allows random access to elements, which makes it efficient for accessing
data by index.
Example:
public class Main {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
System.out.println(numbers[2]); // Output: 3
}
}
Important Points:
Fixed size (cannot be resized once created).
Elements can be of any data type.
2. ArrayList
An implementation of the List interface, part of the Collections Framework.
It allows dynamic resizing (grows as elements are added).
Unlike arrays, an ArrayList can be resized during runtime.
Example:
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
, list.add("Apple");
list.add("Banana");
list.add("Cherry");
System.out.println(list.get(1)); // Output: Banana
}
}
Important Points:
Resizable array implementation.
Allows duplicates.
Supports indexed access, and insertion and removal of elements.
3. LinkedList
Implements the List and Deque interfaces.
It is a doubly linked list, which means each element is connected to both
the next and previous element.
Offers faster insertion and deletion operations compared to ArrayList,
especially in the middle of the list.
Example:
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<>();
list.add("Java");
list.add("Python");
list.add("C++");
list.addFirst("HTML");
System.out.println(list.getFirst()); // Output: HTML
}