
本文介绍如何在java中通过集合(如arraylist)持久化保存每次函数调用生成的内部类对象,并在所有调用结束后统一比较各对象的字段值(如battery差值),从而筛选并输出满足条件(如相邻电池值差>1)的记录。
要实现跨多次函数调用对用户输入的 battery 值进行差值判断(例如:检测相邻两次输入的 battery 差是否大于 1),关键在于打破单次调用的作用域限制——不能仅在 func() 内部创建局部对象后就丢弃,而需将每次创建的对象长期存储、集中管理。
✅ 正确做法:使用 List 保存历史对象
首先,修正命名规范(Java约定:类名首字母大写)——将内部类 in 改为 Inner;同时,将对象容器声明为类成员变量(如 List
import java.util.*;
public class Out {
private Scanner sc = new Scanner(System.in);
private List history = new ArrayList<>(); // 存储所有 Inner 实例
// 内部类:建议定义为 static(若不依赖外部类实例状态),此处保留非 static 亦可
class Inner {
int battery;
int time;
Inner(int battery, int time) {
this.battery = battery;
this.time = time;
}
}
public void func() {
System.out.print("Enter battery and time: ");
int battery = sc.nextInt();
int time = sc.nextInt();
history.add(new Inner(battery, time)); // 每次都存入列表
}
// 新增方法:执行比较与输出逻辑
public void analyze() {
if (history.size() < 2) {
System.out.println("At least two entries required for comparison.");
return;
}
// 遍历相邻元素对:第0&1、1&2、2&3...
for (int i = 0; i < history.size() - 1; i++) {
int diff = Math.abs(history.get(i).battery - history.get(i + 1).battery);
if (diff > 1) {
Inner current = history.get(i);
System.out.printf("Alert: Battery %d (at time %d) differs by >1 from next entry.\n",
current.battery, current.time);
}
}
}
// 示例主流程(演示4次调用)
public static void main(String[] args) {
Out out = new Out();
// 模拟4次输入
out.func(); // 98, 2
out.func(); // 97, 4
out.func(); // 95, 9
out.func(); // 94, 11
out.analyze(); // 输出符合条件的记录
}
} ⚠️ 注意事项与优化建议
- 避免非静态内部类的隐式引用开销:若 Inner 不需要访问 Out 的实例成员,建议改为 static class Inner,防止意外持有外部类引用导致内存泄漏。
- 输入健壮性:生产代码中应加入 sc.hasNextInt() 校验,防止 InputMismatchException。
- 扩展性考虑:如需支持“全局最大差值”或“所有差值>1的组合”,可改用双重循环或流式处理(history.stream()....)。
- 线程安全:若多线程并发调用 func(),需同步 history.add(...) 操作(如用 Collections.synchronizedList(...) 或 CopyOnWriteArrayList)。
通过将对象统一纳入集合管理,你不仅解决了跨调用比较问题,还为后续统计、排序、持久化等操作打下基础——这是面向对象设计中“状态聚合”思想的典型实践。










