slug
type
status
category
summary
date
tags
password
icon
Topic: Arrays and ArrayList
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 namednumbers
and initializes it with the values{1, 2, 3, 4, 5}
.
String[] names
: This declares a string array namednames
and initializes it with the values{"Alice", "Bob", "Charlie"}
.
2. Modifying Array Elements
numbers[0] = 10;
: This changes the first element (index0
) of thenumbers
array from1
to10
.
names[1] = "Barbara";
: This changes the second element (index1
) of thenames
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 thenumbers
array, usingi
as the index. It starts at0
and continues whilei
is less thannumbers.length
(the length of the array).
System.out.println(numbers[i]);
: This prints each element of thenumbers
array. The output will be:
4. Accessing and Printing Array Elements Using Enhanced For Loop
for(String name : names)
: This is an enhancedfor
loop (also known as a "for-each" loop) that iterates over each element of thenames
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 thenames
array. 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.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 rowi
.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 enhancedfor
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.
Code2:
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 thenumbers
array, 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 indexi
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 thenumbers
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 thematrix
array. This element is6
(arrays are zero-indexed).
7. Iterating Over Multidimensional Array
- This nested
for
loop 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 thei
th 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 thenumbers
array, which is5
.
matrix.length
: Returns the number of rows in thematrix
array, 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 3:
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 thejava.util
package, allowing the use of theArrayList
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 themain
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
namednumbers
is created to storeInteger
objects. The<>
(diamond) operator indicates that thisArrayList
will hold elements of typeInteger
.
- Lines 2-4: Elements
1
,2
, and3
are added to thenumbers
ArrayList using theadd()
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 thenumbers
ArrayList.
- Line 3: Each element (
number
) is printed to the console. This loop iterates through all elements in theArrayList
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 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
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:- Using a for-each loop to iterate through each element.
- Printing the
ArrayList
directly, which utilizes thetoString()
method of theArrayList
class to format the output as a list of elements enclosed in square brackets.
Code 4:
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 theArrayList
class from thejava.util
package.
- Creating an ArrayList:
ArrayList<String> fruits = new ArrayList<>();
creates anArrayList
of 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 index1
to"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
for
loop iterates using index. - A
for-each
loop 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.Questions:
- 开发一个简易学生成绩管理
Solutions:
1.学生成绩管理系统solution
- 作者:现代数学启蒙
- 链接:https://www.math1234567.com/article/frq05
- 声明:本文采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。
相关文章