Mastering Arrays and ArrayList in Java: A Complete Guide to the Arrays and ArrayList


Summary of Arrays and ArrayLists in Java
Arrays
Definition: Arrays are fixed-size, homogeneous data structures in Java that store elements of the same type in contiguous memory locations.
Key Features:
Fixed Size: The size is defined at creation and cannot be changed.
Fast Access: Direct index-based access provides O(1) time complexity for retrieval.
Memory Efficient: Minimal overhead due to contiguous storage.
Limitations: No built-in methods for dynamic operations like adding or removing elements.
Common Operations:
Declaration and initialization (e.g., int[] arr = new int[5] or int[] arr = {1, 2, 3})
Accessing/updating elements (e.g., arr[0])
Sorting (using Arrays.sort())
Searching, finding min/max, reversing, and calculating sums.
Use Case: Ideal for scenarios with a known, fixed number of elements and performance-critical applications requiring fast access.
/**
* # Array Operations in Java
*
* This program demonstrates various operations that can be performed on arrays in Java.
* Arrays are fixed-size, homogeneous data structures that store elements in contiguous memory locations.
* Below, we explore common operations like initialization, insertion, updating, sorting, searching, and more.
*
* Copy and paste this code into your Java IDE to try it out!
*/
import java.util.Arrays;
public class ArrayOperations {
public static void main(String[] args) {
// Print a header for clarity
System.out.println("=== Array Operations ===");
/**
* ## 1. Declaration and Initialization
* Arrays can be declared with a fixed size or initialized with values.
*/
int[] numbers = new int[5]; // Array of size 5
int[] initializedArray = {10, 20, 30, 40, 50}; // Initialized with values
/**
* ## 2. Insert Elements
* Populate the array using a loop.
*/
for (int i = 0; i < numbers.length; i++) {
numbers[i] = i * 10; // Insert values 0, 10, 20, 30, 40
}
/**
* ## 3. Display Array
* Use Arrays.toString() to print the array in a readable format.
*/
System.out.println("Array elements: " + Arrays.toString(numbers));
System.out.println("Initialized array: " + Arrays.toString(initializedArray));
/**
* ## 4. Access Specific Element
* Access elements using their index (0-based).
*/
System.out.println("Element at index 2: " + numbers[2]);
/**
* ## 5. Update Element
* Modify an element at a specific index.
*/
numbers[2] = 100;
System.out.println("After update at index 2: " + Arrays.toString(numbers));
/**
* ## 6. Array Length
* Get the size of the array using the length property.
*/
System.out.println("Array length: " + numbers.length);
/**
* ## 7. Sort Array
* Sort the array in ascending order using Arrays.sort().
*/
Arrays.sort(numbers);
System.out.println("Sorted array: " + Arrays.toString(numbers));
/**
* ## 8. Find Maximum Element
* Iterate through the array to find the largest element.
*/
int max = numbers[0];
for (int num : numbers) {
if (num > max) max = num;
}
System.out.println("Maximum element: " + max);
/**
* ## 9. Find Minimum Element
* Iterate through the array to find the smallest element.
*/
int min = numbers[0];
for (int num : numbers) {
if (num < min) min = num;
}
System.out.println("Minimum element: " + min);
/**
* ## 10. Search Element (Linear Search)
* Search for an element and return its index if found.
*/
int searchElement = 100;
boolean found = false;
for (int i = 0; i < numbers
System.out.println("Element " + searchElement + " found at index: " + i);
found = true;
break;
}
}
if (!found) {
System.out.println("Element " + searchElement + " not found");
}
/**
* ## 11. Reverse Array
* Create a new array with elements in reverse order.
*/
int[] reversed = new int[numbers.length];
for (int i = 0; i < numbers.length; i++) {
reversed[i] = numbers[numbers.length - 1 - i];
}
System.out.println("Reversed array: " + Arrays.toString(reversed));
/**
* ## 12. Sum of Elements
* Calculate the sum of all elements in the array.
*/
int sum = 0;
for (int num : numbers) {
sum += num;
}
System.out.println("Sum of elements: " + sum);
}
}
ArrayLists
Definition: ArrayLists are dynamic, resizable data structures in Java, part of the java.util package, that can grow or shrink as needed.
Key Features:
Dynamic Size: Automatically resizes when elements are added or removed.
Flexible Operations: Built-in methods for adding, removing, sorting, and searching elements.
Type-Safe with Generics: Supports any data type with type safety (e.g., ArrayList<String>).
Limitations: Slightly slower than arrays due to dynamic resizing and additional method overhead.
Common Operations:
Declaration and initialization (e.g., ArrayList<String> list = new ArrayList<>())
Adding/removing elements (e.g., list.add(), list.remove())
Accessing/updating elements (e.g., list.get(), list.set())
Sorting (using Collections.sort()), reversing, and checking size/emptiness.
Use Case: Best for scenarios requiring frequent additions/removals or when the number of elements is unknown.
/**
* # ArrayList Operations in Java
*
* This program showcases various operations on ArrayList, a dynamic, resizable data structure in Java.
* Unlike arrays, ArrayLists can grow or shrink in size and provide built-in methods for common operations.
* Below, we demonstrate adding, removing, updating, sorting, and other operations on an ArrayList.
*
* Copy and paste this code into your Java IDE to experiment with ArrayList!
*/
import java.util.ArrayList;
import java.util.Collections;
public class ArrayListOperations {
public static void main(String[] args) {
// Print a header for clarity
System.out.println("=== ArrayList Operations ===");
/**
* ## 1. Declaration and Initialization
* Create an ArrayList to store strings (can store any data type).
*/
ArrayList<String> fruits = new ArrayList<>();
/**
* ## 2. Add Elements
* Add elements to the ArrayList using the add() method.
*/
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
fruits.add("Mango");
System.out.println("ArrayList: " + fruits);
/**
* ## 3. Add Element at Specific Index
* Insert an element at a specific position using add(index, element).
*/
fruits.add(1, "Grape");
System.out.println("After adding Grape at index 1: " + fruits);
/**
* ## 4. Access Specific Element
* Retrieve an element using get(index).
*/
System.out.println("Element at index 2: " + fruits.get(2));
/**
* ## 5. Update Element
* Modify an element at a specific index using set(index, element).
*/
fruits.set(2, "Pineapple");
System.out.println("After updating index 2: " + fruits);
/**
* ## 6. Remove Element by Value
* Remove an element by its value using remove(element).
*/
fruits.remove("Banana");
System.out.println("After removing Banana: " + fruits);
/**
* ## 7. Remove Element by Index
* Remove an element at a specific index using remove(index).
*/
fruits.remove(0);
System.out.println("After removing element at index 0: " + fruits);
/**
* ## 8. Get Size
* Get the number of elements in the ArrayList using size().
*/
System.out.println("ArrayList size: " + fruits.size());
/**
* ## 9. Check if Element Exists
* Check if an element exists using contains(element).
*/
String searchFruit = "Mango";
if (fruits.contains(searchFruit)) {
System.out.println(searchFruit + " exists in ArrayList");
} else {
System.out.println(searchFruit + " does not exist in ArrayList");
}
/**
* ## 10. Sort ArrayList
* Sort the ArrayList in ascending order using Collections.sort().
*/
Collections.sort(fruits);
System.out.println("Sorted ArrayList: " + fruits);
/**
* ## 11. Reverse ArrayList
* Reverse the order of elements using Collections.reverse().
*/
Collections.reverse(fruits);
System.out.println("Reversed ArrayList: " + fruits);
/**
* ## 12. Check if ArrayList is Empty
* Check if the ArrayList is empty using isEmpty().
*/
System.out.println("Is ArrayList empty? " + fruits.isEmpty());
/**
* ## 13. Clear ArrayList
* Remove all elements using clear().
*/
fruits.clear();
System.out.println("After clearing ArrayList: " + fruits);
/**
* ## 14. Verify Emptiness After Clear
* Confirm the ArrayList is empty after clearing.
*/
System.out.println("Is ArrayList empty after clear? " + fruits.isEmpty());
}
}
Key Differences
Feature | Array | ArrayList |
Size | Fixed | Dynamic |
Performance | Faster (direct access) | Slightly slower (resizing) |
Functionality | Limited (manual operations) | Rich (built-in methods) |
Type | Primitive or Object | Objects only (via generics) |
When to Use
Use Arrays for fixed-size, performance-critical tasks (e.g., numerical computations).
Use ArrayLists for dynamic, flexible data manipulation (e.g., lists that grow/shrink).
Subscribe to my newsletter
Read articles from Prathamesh Karatkar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
