Java创建数组(定长数组和变长数组创建,并以基本类型int,以及应用类型Animal类为例)
两种创建数组方式的详细 Java 代码示例:
代码解释:
-
定长数组:
int[] arrA = new int[5];:创建了一个长度为 5 的int类型数组。Animal[] arrB = new Animal[3];:创建了一个长度为 3 的Animal类型数组。- 数组长度在创建时确定,后续不能改变。
-
变长数组
ArrayList:ArrayList<Integer> arrListA = new ArrayList<>();:创建了一个存储Integer类型元素的ArrayList。ArrayList<Animal> arrListB = new ArrayList<>();:创建了一个存储Animal类型元素的ArrayList。ArrayList的长度可以动态变化,通过add方法添加元素。
-
元素访问和操作:
- 对于定长数组,使用索引访问(或foreach进行遍历)和修改元素。
- 对于
ArrayList,使用add方法添加元素,使用get方法访问元素。
运行结果:
代码会打印出定长数组和变长数组中存储的元素,以及调用 Animal 对象的 makeSound 方法的结果。
import java.util.ArrayList;
// 定义一个 Animal 类
class Animal {
// 这里可以添加 Animal 类的属性和方法
public void makeSound() {
System.out.println("Animal makes a sound");
}
}
public class ArrayCreationExample {
public static void main(String[] args) {
// 1. 定长数组
// 创建基本类型 int 的定长数组
int[] arrA = new int[5];
// 给数组元素赋值
for (int i = 0; i < arrA.length; i++) {
arrA[i] = i;
}
// 创建引用类型 Animal 的定长数组
Animal[] arrB = new Animal[3];
// 给数组元素赋值
for (int i = 0; i < arrB.length; i++) {
arrB[i] = new Animal();
}
// 2. 变长数组 ArrayList
// 创建存储基本类型包装类 Integer 的 ArrayList
ArrayList<Integer> arrListA = new ArrayList<>();
// 向 ArrayList 中添加元素
for (int i = 0; i < 5; i++) {
arrListA.add(i);
}
// 创建存储引用类型 Animal 的 ArrayList
ArrayList<Animal> arrListB = new ArrayList<>();
// 向 ArrayList 中添加元素
for (int i = 0; i < 3; i++) {
arrListB.add(new Animal());
}
// 打印定长数组 arrA 的元素,foreach循环遍历
System.out.println("定长数组 arrA 的元素:");
for (int num : arrA) {
System.out.print(num + " ");
}
System.out.println();
// 调用定长数组 arrB 中元素的方法,foreach循环遍历
System.out.println("定长数组 arrB 中元素调用方法:");
for (Animal animal : arrB) {
animal.makeSound();
}
// 打印变长数组 arrListA 的元素,foreach循环遍历
System.out.println("变长数组 arrListA 的元素:");
for (int num : arrListA) {
System.out.print(num + " ");
}
System.out.println();
// 调用变长数组 arrListB 中元素的方法,foreach循环遍历
System.out.println("变长数组 arrListB 中元素调用方法:");
for (Animal animal : arrListB) {
animal.makeSound();
}
}
}

浙公网安备 33010602011771号