slug
type
status
category
date
summary
tags
password
icon
Topic: Arrays and ArrayList
Part 1 基础训练 Code 1:
This Java program demonstrates various operations related to arrays, including initialization, modification, access, and iteration through both single-dimensional and multi-dimensional arrays. Here's a detailed explanation of each part of the code:
1. Declaring and Initializing Arrays
int[] numbers: This declares an integer array namednumbersand initializes it with the values{1, 2, 3, 4, 5}.
String[] names: This declares a string array namednamesand initializes it with the values{"Alice", "Bob", "Charlie"}.
2. Modifying Array Elements
numbers[0] = 10;: This changes the first element (index0) of thenumbersarray from1to10.
names[1] = "Barbara";: This changes the second element (index1) of thenamesarray from"Bob"to"Barbara".
3. Accessing and Printing Array Elements Using Traditional For Loop
for(int i = 0; i < numbers.length; i++): This loop iterates over thenumbersarray, usingias the index. It starts at0and continues whileiis less thannumbers.length(the length of the array).
System.out.println(numbers[i]);: This prints each element of thenumbersarray. The output will be:
4. Accessing and Printing Array Elements Using Enhanced For Loop
for(String name : names): This is an enhancedforloop (also known as a "for-each" loop) that iterates over each element of thenamesarray.nameis a temporary variable that holds the value of each element in the array during each iteration.
System.out.println(name);: This prints each element of thenamesarray. The output will be:
5. Declaring and Initializing a Multidimensional Array
int[][] matrix: This declares a two-dimensional integer array namedmatrix. It represents a matrix with two rows and three columns. The first row contains{1, 2, 3}, and the second row contains{4, 5, 6}.
6. Printing a Multidimensional Array Using Nested Loops
- Outer Loop (
for(int i = 0; i < matrix.length; i++)): This iterates over each row of thematrix.matrix.lengthgives the number of rows in the matrix.
- Inner Loop (
for(int j = 0; j < matrix[i].length; j++)): This iterates over each element in the current rowi.matrix[i].lengthgives the number of columns in the current row.
System.out.print(matrix[i][j] + " ");: This prints each element of the matrix in a row, separated by a space.
System.out.println();: This moves to the next line after printing all elements of the current row.
The output for the matrix will be:
Summary
- The program illustrates basic operations on single-dimensional and multi-dimensional arrays, including initialization, element modification, and traversal using different loop constructs.
- It uses both traditional
forloops and enhancedforloops to demonstrate different methods of iterating through array elements.
- It also shows how to work with multidimensional arrays by using nested loops for element access and printing.
Code 2:
Here's a complete executable Java code that demonstrates the basics of using an
ArrayList. It includes examples of adding, accessing, modifying, and removing elements, as well as iterating over the list.Explanation of the Code:
- Import Statement:
import java.util.ArrayList;is used to import theArrayListclass from thejava.utilpackage.
- Creating an ArrayList:
ArrayList<String> fruits = new ArrayList<>();creates anArrayListof typeString.
- Adding Elements:
fruits.add("Apple");adds the string"Apple"to the list.
- Accessing Elements:
fruits.get(0);accesses the element at index0.
- Modifying Elements:
fruits.set(1, "Blueberry");modifies the element at index1to"Blueberry".
- Removing Elements:
fruits.remove(2);removes the element at index2.fruits.remove("Date");removes the element"Date"from the list.
- Checking for an Element:
fruits.contains("Apple");checks if"Apple"is in the list.
- Size of the ArrayList:
fruits.size();returns the number of elements in the list.
- Iteration:
- A
forloop iterates using index. - A
for-eachloop iterates through each element directly.
- Clearing the ArrayList:
fruits.clear();removes all elements from the list.
You can copy this code into a
.java file and run it using a Java compiler to see how ArrayList works.Part 2 提升训练
Code 3:
This
ArrayExamples class demonstrates various operations on single-dimensional and multi-dimensional arrays in Java. Here's a detailed explanation of the code:1. Single-Dimensional Array Declaration and Initialization
int[] numbers: Declares a single-dimensional array of integers.
{1, 2, 3, 4, 5}: Initializes the array with five elements: 1, 2, 3, 4, and 5.
2. Accessing Array Elements
numbers[0]: Accesses the first element of thenumbersarray, which is1.
3. Iterating Over Array using for loop
- This loop iterates through the array using an index
i.
numbers.length: Returns the size of the array (5 in this case).
numbers[i]: Accesses the element at the indexiof the array and prints it.
4. Iterating Over Array using for-each loop
- The enhanced for loop (
for-each) iterates through each element in thenumbersarray directly without using an index.
number: Represents the current element in the iteration, and it prints each element sequentially.
5. Multidimensional Array Declaration and Initialization
int[][] matrix: Declares a two-dimensional array of integers.
{ {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }: Initializes the array as a 3x3 matrix with elements arranged in rows and columns.
6. Accessing Elements of Multidimensional Array
matrix[1][2]: Accesses the element at row 1, column 2 of thematrixarray. This element is6(arrays are zero-indexed).
7. Iterating Over Multidimensional Array
- This nested
forloop iterates through each element of the two-dimensional arraymatrix.
matrix.length: Returns the number of rows in thematrix(3 in this case).
matrix[i].length: Returns the number of columns in theith row (3 in this case).
System.out.print(matrix[i][j] + " "): Prints each element in the current row followed by a space.
System.out.println(): Moves to the next line after each row is printed.
8. Using Length Property
numbers.length: Returns the size of thenumbersarray, which is5.
matrix.length: Returns the number of rows in thematrixarray, which is3.
matrix[0].length: Returns the number of columns in the first row of thematrix, which is3.
This class provides a fundamental demonstration of how to declare, initialize, and iterate over single-dimensional and multi-dimensional arrays in Java, as well as how to use the
length property to determine the size of the arrays.code 4:
This Java code demonstrates how to create and print the contents of an
ArrayList using two different methods. Here is a breakdown of the code:1. Import Statement:
- This imports the
ArrayListclass from thejava.utilpackage, allowing the use of theArrayListdata structure, which is a resizable array that can hold elements of any type (in this case,Integer).
2. Class Declaration:
- This declares a public class named
PrintArrayListExample. The class contains themainmethod, which is the entry point for the program.
3. Main Method:
- This is the main method where the execution of the program begins.
4. Creating and Initializing an ArrayList:
- Line 1: An
ArrayListnamednumbersis created to storeIntegerobjects. The<>(diamond) operator indicates that thisArrayListwill hold elements of typeInteger.
- Lines 2-4: Elements
1,2, and3are added to thenumbersArrayList using theadd()method.
5. Method 1: Printing Using a For-Each Loop:
- Line 1: A message is printed to indicate that the
ArrayListwill be printed using a for-each loop.
- Line 2: A for-each loop is used to iterate over each element (
number) in thenumbersArrayList.
- Line 3: Each element (
number) is printed to the console. This loop iterates through all elements in theArrayListand prints each one on a new line.
6. Method 2: Printing the ArrayList Directly:
- Line 1: A message is printed to indicate that the
ArrayListwill be printed directly.
- Line 2: The entire
numbersArrayList is printed directly usingSystem.out.println(numbers);. TheArrayList'stoString()method is called implicitly, which returns a string representation of the list. The output will look like[1, 2, 3].
Output of the Program:
- For-Each Loop Output: Each element of the
ArrayListis printed on a new line.
- Direct Print Output: The entire
ArrayListis printed in a single line in a bracketed format.
Summary
The code demonstrates two common ways to print the elements of an
ArrayList in Java:- Using a for-each loop to iterate through each element.
- Printing the
ArrayListdirectly, which utilizes thetoString()method of theArrayListclass to format the output as a list of elements enclosed in square brackets.
Part 3 Quiz
Here are some AP Computer Science A-style questions focusing on arrays and ArrayLists along with their answers:
1. Array Basics
Question: What is the output of the following code?
Answer:
Answer:
9Explanation: The index 3 in the array
arr corresponds to the 4th element, which is 9.2. Array Length
Question: What will happen if you try to access an index that is out of bounds in an array?
Answer
Answer:
ArrayIndexOutOfBoundsExceptionExplanation: The array
arr has indices 0 to 3. Trying to access arr[4] will throw an ArrayIndexOutOfBoundsException.3. ArrayList Basic Operations
Question: What is the output of the following code?
Answer
Answer:
[A, C]Explanation: The element at index 1 ("B") is removed, leaving "A" and "C" in the list.
4. Array vs. ArrayList
Question: Which of the following statements is true?
- A) Arrays can dynamically change their size.
- B) ArrayLists require you to specify the size at the time of creation.
- C) Arrays have a fixed size once created.
- D) ArrayLists can only store primitive data types.
Answer
Answer:
C) Arrays have a fixed size once created.Explanation: Arrays have a fixed size after creation, while ArrayLists can dynamically resize. ArrayLists can only store objects, not primitive data types directly.
5. Traversing an Array
Question: What is the correct way to sum all elements in the following array?
- A)
int sum = numbers[0] + numbers[1] + numbers[2] + numbers[3];
- B)
int sum = 0; for(int i = 0; i < numbers.length; i++) sum += numbers[i];
- C)
int sum = 0; for(int num : numbers) sum += num;
- D) All of the above.
Answer
Answer: D) All of the above.
Explanation: A, B, and C correctly traverse the array and sum the elements.
6. ArrayList Manipulation
Question: What is the output of the following code?
Answer
Answer:
[0, 2, 10, 6, 8]Explanation: The ArrayList initially contains
[0, 2, 4, 6, 8]. The set(2, 10) replaces the element at index 2 (value 4) with 10.7. Array Sorting
Question: What is the state of the array after the following code executes?
Answer
Answer:
[1, 1, 3, 4, 5]Explanation: The
Arrays.sort(arr) method sorts the array in ascending order.8. Removing Elements from ArrayList
Question: What is the output of the following code?
Answer
Answer:
2Explanation: After removing "cat", the list contains 2 elements ("dog" and "bird").
These questions should provide a good practice for understanding the concepts of arrays and ArrayLists in AP Computer Science A.
- 作者:现代数学启蒙
- 链接:https://www.math1234567.com/article/frq05b
- 声明:本文采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。





