slug
type
status
category
summary
date
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 named numbers and initializes it with the values {1, 2, 3, 4, 5}.
  • String[] names: This declares a string array named names and initializes it with the values {"Alice", "Bob", "Charlie"}.

2. Modifying Array Elements

  • numbers[0] = 10;: This changes the first element (index 0) of the numbers array from 1 to 10.
  • names[1] = "Barbara";: This changes the second element (index 1) of the names array 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 the numbers array, using i as the index. It starts at 0 and continues while i is less than numbers.length (the length of the array).
  • System.out.println(numbers[i]);: This prints each element of the numbers array. The output will be:

    4. Accessing and Printing Array Elements Using Enhanced For Loop

    • for(String name : names): This is an enhanced for loop (also known as a "for-each" loop) that iterates over each element of the names array. name is 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 the names array. The output will be:

      5. Declaring and Initializing a Multidimensional Array

      • int[][] matrix: This declares a two-dimensional integer array named matrix. 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 the matrix. matrix.length gives 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 row i. matrix[i].length gives 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 for loops and enhanced for loops 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:

      1. Import Statement: import java.util.ArrayList; is used to import the ArrayList class from the java.util package.
      1. Creating an ArrayList: ArrayList<String> fruits = new ArrayList<>(); creates an ArrayList of type String.
      1. Adding Elements: fruits.add("Apple"); adds the string "Apple" to the list.
      1. Accessing Elements: fruits.get(0); accesses the element at index 0.
      1. Modifying Elements: fruits.set(1, "Blueberry"); modifies the element at index 1 to "Blueberry".
      1. Removing Elements: fruits.remove(2); removes the element at index 2. fruits.remove("Date"); removes the element "Date" from the list.
      1. Checking for an Element: fruits.contains("Apple"); checks if "Apple" is in the list.
      1. Size of the ArrayList: fruits.size(); returns the number of elements in the list.
      1. Iteration:
          • A for loop iterates using index.
          • A for-each loop iterates through each element directly.
      1. 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 the numbers array, which is 1.

      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 index i of the array and prints it.

      4. Iterating Over Array using for-each loop

      • The enhanced for loop (for-each) iterates through each element in the numbers array 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 the matrix array. This element is 6 (arrays are zero-indexed).

      7. Iterating Over Multidimensional Array

      • This nested for loop iterates through each element of the two-dimensional array matrix.
      • matrix.length: Returns the number of rows in the matrix (3 in this case).
      • matrix[i].length: Returns the number of columns in the ith 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 the numbers array, which is 5.
      • matrix.length: Returns the number of rows in the matrix array, which is 3.
      • matrix[0].length: Returns the number of columns in the first row of the matrix, which is 3.
      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 ArrayList class from the java.util package, allowing the use of the ArrayList data 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 the main method, 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 ArrayList named numbers is created to store Integer objects. The <> (diamond) operator indicates that this ArrayList will hold elements of type Integer.
      • Lines 2-4: Elements 1, 2, and 3 are added to the numbers ArrayList using the add() method.

      5. Method 1: Printing Using a For-Each Loop:

      • Line 1: A message is printed to indicate that the ArrayList will be printed using a for-each loop.
      • Line 2: A for-each loop is used to iterate over each element (number) in the numbers ArrayList.
      • Line 3: Each element (number) is printed to the console. This loop iterates through all elements in the ArrayList and prints each one on a new line.

      6. Method 2: Printing the ArrayList Directly:

      • Line 1: A message is printed to indicate that the ArrayList will be printed directly.
      • Line 2: The entire numbers ArrayList is printed directly using System.out.println(numbers);. The ArrayList's toString() 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 ArrayList is printed on a new line.
      • Direct Print Output: The entire ArrayList is 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:
      1. Using a for-each loop to iterate through each element.
      1. Printing the ArrayList directly, which utilizes the toString() method of the ArrayList class 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: 9
      Explanation: 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: ArrayIndexOutOfBoundsException
      Explanation: 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: 2
      Explanation: 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.
      CSAWESOME SOLUTIONSDifferent Types of ArrayList
      Loading...