Array
An Array in Java is a data structure used to store multiple values of the same type in a single variable. Arrays are fixed in size, meaning the number of elements in an array is defined when the array is created and cannot be changed after that.
- Declaration: You need to specify the type of elements the array will hold.
- Accessing Elements: Elements can be accessed via an index (starting from 0).
1 2 3 |
int[] numbers = new int[5]; // Array of 5 integers numbers[0] = 10; // Setting the first element to 10 numbers[1] = 20; // Setting the second element to 20 |
ArrayList
An ArrayList is part of Java’s collection framework and provides a dynamic array-like structure that can grow and shrink in size as elements are added or removed. Unlike arrays, ArrayLists are not fixed in size, and they can dynamically adjust to accommodate changes in the number of elements.
- Declaration: It is a generic class, meaning you specify the type of objects it will hold.
- Accessing Elements: Elements can be accessed using methods like
get()
.
1 2 3 4 |
ArrayList<Integer> list = new ArrayList<>(); // ArrayList of Integers list.add(10); // Adding elements list.add(20); list.add(30); |
Differences between Arrays and ArrayList
Feature | Array | ArrayList |
---|---|---|
Size | Fixed size | Dynamic size |
Type of Elements | Can store both primitive and object types | Can only store objects (use wrapper classes for primitives) |
Performance | Faster, fixed memory allocation | Slightly slower due to resizing and extra overhead |
Flexibility | Limited functionality | Extensive methods (add, remove, contains, etc.) |
Memory Usage | More memory-efficient | More memory overhead due to resizing and object storage |
Type of Data | Can be homogeneous or heterogeneous | Must be homogeneous (same data type) |
Access Time | Constant time (O(1)) | Constant time (O(1)) for access, but may vary with resizing |
Resizing | Cannot resize | Automatically resizes as elements are added or removed |
Example | int[] arr = new int[5]; |
ArrayList<Integer> list = new ArrayList<>(); |