Module 2: Arrays
Module Overview
Arrays are fundamental data structures in Java used to store collections of elements. In this module, you'll learn how to create, manipulate, and work with arrays efficiently.
Learning Objectives
- Declare and initialize arrays of primitive and reference types
- Access array elements using index notation
- Manipulate array data through loops and standard operations
- Work with multi-dimensional arrays
- Understand common array algorithms (search, sort, transformation)
Array Concepts Explained
Array Declaration and Initialization
Learn how to create arrays and initialize them with values.
// Array declaration
int[] numbers; // Preferred style
int scores[]; // Also valid but less common
// Array initialization
numbers = new int[5]; // Creates array of 5 integers, all initialized to 0
// Declaration and initialization in one step
int[] primes = {2, 3, 5, 7, 11};
// Creating an array with new and initializing values
String[] days = new String[] {"Mon", "Tue", "Wed", "Thu", "Fri"};
Accessing and Modifying Array Elements
Arrays use zero-based indexing for accessing elements.
int[] numbers = {10, 20, 30, 40, 50};
// Accessing elements
int firstNumber = numbers[0]; // 10
int thirdNumber = numbers[2]; // 30
// Modifying elements
numbers[1] = 25; // Changes 20 to 25
// Common properties
int length = numbers.length; // 5 (the number of elements)
// Error: Accessing an index out of bounds
// int invalid = numbers[5]; // ArrayIndexOutOfBoundsException
Iterating Through Arrays
Learn different ways to loop through array elements.
int[] numbers = {10, 20, 30, 40, 50};
// Using a for loop with index
for (int i = 0; i < numbers.length; i++) {
System.out.println("Element at index " + i + ": " + numbers[i]);
}
// Using enhanced for loop (for-each)
for (int number : numbers) {
System.out.println("Element value: " + number);
}
Multi-dimensional Arrays
Arrays can have multiple dimensions, like tables with rows and columns.
// 2D array declaration and initialization
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Accessing elements in a 2D array
int element = matrix[1][2]; // Row 1, Column 2: value is 6
// Iterating through a 2D array
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[row].length; col++) {
System.out.print(matrix[row][col] + " ");
}
System.out.println(); // New line after each row
}
Common Array Operations
Fundamental operations performed on arrays.
// Finding the maximum value
int[] values = {23, 44, 12, 99, 8};
int max = values[0];
for (int i = 1; i < values.length; i++) {
if (values[i] > max) {
max = values[i];
}
}
System.out.println("Maximum value: " + max); // 99
// Summing array elements
int[] numbers = {10, 20, 30, 40, 50};
int sum = 0;
for (int number : numbers) {
sum += number;
}
System.out.println("Sum: " + sum); // 150
// Copying arrays
int[] original = {1, 2, 3, 4, 5};
int[] copy = new int[original.length];
// Manual copy
for (int i = 0; i < original.length; i++) {
copy[i] = original[i];
}
// Using System.arraycopy
System.arraycopy(original, 0, copy, 0, original.length);
// Using Arrays.copyOf
import java.util.Arrays;
int[] anotherCopy = Arrays.copyOf(original, original.length);
Practical Applications
Arrays are widely used in programming for various purposes:
- Storing and processing collections of data
- Implementing data structures like stacks, queues, and lists
- Representing multi-dimensional data (tables, matrices, grids)
- Efficient access to sequential data
- Statistical analysis and calculations
- Image processing and manipulation
Additional Resources
Mastery Task 8 - Arrays
Mastery Task Guidelines
Mastery Tasks are opportunities to test your knowledge and understanding through code. When a mastery task is shown in a module, it means that we've covered all the concepts that you need to complete that task. You will want to make sure you finish them by the end of the week to stay on track and complete the unit.
Each mastery task must pass 100% of the automated tests and code styling checks to pass each unit. Your code must be your own. If you have any questions, feel free to reach out for support.
Arrays
We are going to change how the player object stores items like keys and shovels. Instead of storing them in separate objects, we're going to store them in an array. This will require us to loop through the array to perform various actions.
Backpack
Open the Backpack class and read the comments.
Fill in the TODOs to complete the object.
Player
In the Player object, do the following:
- Remove the Key and Shovel objects and replace them with a Backpack object with scope of private. This will cause some issues with the setters and getters.
- Rewrite the logic for the setters and getters so they store/retrieve the items using the backpack. For the getters, use a default String to get the object. ("key" for getKey, "shovel" for getShovel).
- Update the method addItem that takes an item of type Tangible. This method will then pass the item onto the backpack's addItem call.
- Update the method getItem that takes a String name and returns an object of type Tangible. It will pass this along to the backback's getItem method.
- Update the method removeItem that takes a Tangible item. This will pass the item onto the backpack's removeItem method.
- Create the method printItems that calls the backpack's printItems method.
- You may need to update some functions such as setShovel, setKey, etc, so they become convenient functions that simply call addItem.
GameController
With the backpack now complete, we need to include logic for the CommandVerb INVENTORY (you may need to update CommandVerb to account for the INVENTORY enum if it's not already handled).
In GameController find the method applyCommand. Add INVENTORY to the switch statement's cases and have it call player.printItems.
Testing
To run the tests for this assignment, run the following:
./gradlew test --tests com.adventure.MT8
or by right-clicking the MT8 file and selecting "Run 'MT8'"
You can check your code styling by running the linter with the following command:
./gradlew checkstyleMain
You can run the game by going to the Main class and clicking on the run icon to the left of the main() method.