Hello readers! This is a simple article introducing one of the simplest and most commonly used data structures… Arrays!
What is an Array?
An array is a collection of elements stored at contiguous memory locations. It allows you to store multiple values of the same type in a single variable, which can be accessed using an index.
Key Concepts
- Creating an Array
- Declaration: Define an array and specify its size.
- Initialization: Assign values to the array elements.
- Accessing Array Elements
- Indexing: Access elements using their index. Remember that array indices typically start at 0.
- Basic Operations
- Traversal: Loop through the array to access or display all elements.
- Insertion: Add new elements to the array (for fixed-size arrays, this involves creating a new array and copying elements).
- Deletion: Remove elements from the array (similar to insertion, it may require creating a new array).
Example in Java
Here’s a simple example of how to work with arrays in Java:
public class ArrayExample {
public static void main(String[] args) {
// Declare and initialize an array
int[] numbers = {1, 2, 3, 4, 5};
// Accessing and displaying elements
for (int i = 0; i < numbers.length; i++) {
System.out.println("Element at index " + i + ": " + numbers[i]);
}
// Modifying an element
numbers[2] = 10; // Changing the value at index 2
System.out.println("Modified element at index 2: " + numbers[2]);
}
}
When to Use Arrays
Arrays are useful when:
- You need to store multiple values of the same type.
- You know the number of elements in advance.
- You need fast access to elements using indices.
Limitations
- Fixed Size: Once an array is created, its size cannot be changed.
- Insertion/Deletion Complexity: Adding or removing elements can be cumbersome with fixed-size arrays.
Works Cited
- GeeksforGeeks. “Arrays in Java.” GeeksforGeeks, 2024, https://www.geeksforgeeks.org/arrays-in-java/.
- Techopedia. “Array Data Structure.” Techopedia, 2024, https://www.techopedia.com/definition/1241/array-data-structure.