
本文详解如何将原代码中基于 Rectangle[] 的静态数组升级为 ArrayList<Rectangle>,实现灵活添加矩形、动态扩容,并提供完整的可运行示例与最佳实践建议。
本文详解如何将原代码中基于 `rectangle[]` 的静态数组升级为 `arraylist
在 Java 中,ArrayList 是比原始数组更灵活、更符合面向对象设计的集合类型。它支持动态增删元素、无需预设容量,且天然适配增强型 for 循环(for-each)和函数式操作。要将原程序中 Rectangle[] rectangles = new Rectangle[3]; 的写法迁移到 ArrayList,核心在于三点:声明泛型列表、改用 add() 动态插入、用 for-each 遍历访问。
以下是重构后的完整 main 方法(假设 Rectangle 类已正确定义,含无参构造、双参构造、getWidth()、getHeight()、getArea() 和 getPerimeter() 方法):
import java.util.*;
import java.util.UUID;
public static void main(String[] args) {
List<Rectangle> rectangles = new ArrayList<>(); // ✅ 声明泛型 ArrayList,类型安全
Scanner input = new Scanner(System.in);
System.out.println("Enter rectangles one by one. Type 'N' to finish.");
while (true) {
System.out.println("Do you want to enter width and height? (Y/N)");
String choice = input.next().trim().toLowerCase();
if (choice.equals("n")) {
break; // ✅ 用户主动终止输入
} else if (choice.equals("y")) {
try {
System.out.print("Enter width: ");
double width = input.nextDouble();
System.out.print("Enter height: ");
double height = input.nextDouble();
rectangles.add(new Rectangle(width, height)); // ✅ 动态添加,无需索引
} catch (InputMismatchException e) {
System.out.println("Invalid input. Please enter numeric values.");
input.nextLine(); // 清除错误输入缓存
continue;
}
} else {
System.out.println("Please enter 'Y' or 'N'.");
input.nextLine(); // 消耗非法字符
continue;
}
}
System.out.println("\nThe rectangles are:");
int index = 1;
for (Rectangle rect : rectangles) { // ✅ for-each 遍历,简洁清晰
System.out.printf("Rectangle %d: width = %.2f, height = %.2f%n",
index++, rect.getWidth(), rect.getHeight());
System.out.printf("→ Area = %.2f, Perimeter = %.2f%n",
rect.getArea(), rect.getPerimeter());
}
input.close();
}? 关键改进说明:
- 类型安全:List<Rectangle> 明确限定集合中只存储 Rectangle 实例,编译期即可捕获类型错误;
- 动态性:无需预先指定数量,用户可自由决定创建多少个矩形;
- 健壮性:增加了输入异常处理(如非数字输入),避免程序崩溃;
- 可读性与维护性:使用 for-each 替代传统索引循环,逻辑更聚焦于业务而非下标管理;
- 扩展建议:若需唯一标识每个矩形(如日志追踪或 GUI 交互),推荐在 Rectangle 类中引入 UUID id 字段(如使用 record Rectangle(UUID id, double width, double height)),并在构造时调用 UUID.randomUUID() 自动生成——这比依赖循环序号更可靠、线程安全且支持后续任意顺序访问。
✅ 总结:从数组到 ArrayList 不仅是语法替换,更是编程思维的升级——拥抱动态性、类型安全与集合工具链,让代码更健壮、易扩展、易测试。

















