
本文介绍如何在java中通过集合容器(如list)保存多次调用函数时生成的内部类对象,并对其中的字段(如battery值)进行跨实例比较与条件筛选。
在实际开发中,若需在多次函数调用中动态创建同一类的多个对象(例如每次读取一组 battery 和 time 值),并后续对这些对象的属性进行关联分析(如检测相邻电池值的突变),直接在局部作用域内创建对象会导致数据丢失。因此,必须将对象持久化存储于函数外部可访问的集合中。
以下是完整、可运行的解决方案(已优化命名规范、结构清晰、逻辑严谨):
import java.util.*;
public class Outer { // ✅ 类名首字母大写(遵循Java命名约定)
private Scanner sc = new Scanner(System.in);
private List records = new ArrayList<>(); // ✅ 使用成员变量存储所有实例
// ✅ 内部类名也应大写(Inner 而非 in)
private static class Inner {
final int battery; // ✅ 使用 final 明确不可变语义
final int time;
Inner(int battery, int time) {
this.battery = battery;
this.time = time;
}
}
public void func() {
System.out.print("Enter battery level: ");
int battery = sc.nextInt();
System.out.print("Enter time (e.g., minutes): ");
int time = sc.nextInt();
records.add(new Inner(battery, time)); // ✅ 每次调用都存入列表
}
// ✅ 新增分析方法:检测相邻记录间 battery 差值 > 1 的情况
public void analyzeAndPrint() {
if (records.size() < 2) {
System.out.println("At least two records are required for comparison.");
return;
}
System.out.println("\nRecords where previous battery differs from next by > 1:");
for (int i = 0; i < records.size() - 1; i++) {
int currentBattery = records.get(i).battery;
int nextBattery = records.get(i + 1).battery;
int diff = Math.abs(currentBattery - nextBattery); // ✅ 取绝对值,兼容升/降变化
if (diff > 1) {
System.out.printf("→ Record %d: battery=%d, time=%d%n",
i + 1, currentBattery, records.get(i).time);
}
}
}
// ✅ 示例主流程(模拟4次调用)
public static void main(String[] args) {
Outer outer = new Outer();
// 模拟用户输入(实际中由 Scanner 交互获取)
// 输入序列:98 2 → 97 4 → 95 9 → 94 11
// 对应差值:|98-97|=1 ❌, |97-95|=2 ✅, |95-94|=1 ❌ → 仅第2条记录(97,4)应被打印
// 在真实场景中,此处替换为循环调用 outer.func()
outer.func(); // 98 2
outer.func(); // 97 4
outer.func(); // 95 9
outer.func(); // 94 11
outer.analyzeAndPrint();
}
} 关键要点说明:
- ✅ 避免匿名内部类陷阱:原代码中 in 是非静态内部类,会隐式持有外部类实例引用;若需长期存储,建议改为 static 内部类(如本例),防止内存泄漏。
- ✅ 集合选择:ArrayList 适合随机访问和顺序遍历;若需频繁首尾插入/删除,可选 LinkedList。
- ✅ 比较逻辑健壮性:使用 Math.abs() 处理上升或下降突变;明确边界条件(如记录数不足2时提前返回)。
- ✅ 封装性与职责分离:func() 专注数据采集,analyzeAndPrint() 专注业务逻辑,符合单一职责原则。
运行上述代码,输入示例数据后,将准确输出:
→ Record 2: battery=97, time=4
即满足“相邻电池值差大于1”的首个触发点——正是题目要求的第2次调用结果。










