publicTaskManager(List<List<Integer>> tasks) { this.tasks = newPriorityQueue<>( (a, b) -> a.get(2).equals(b.get(2)) ? b.get(1) - a.get(1) : b.get(2) - a.get(2) ); for (List<Integer> task : tasks) { this.tasks.add(newArrayList<>(task)); } } publicvoidadd(int userId, int taskId, int priority) { tasks.add(newArrayList<>(Arrays.asList(userId, taskId, priority))); } publicvoidedit(int taskId, int newPriority) { List<Integer> toRemove; for (List<Integer> task : tasks) { if (task.get(1) == taskId) { toRemove = task; break; } } if (toRemove != null) { tasks.remove(toRemove); tasks.add(newArrayList<>(Arrays.asList(toRemove.get(0), taskId, newPriority))); } } publicvoidrmv(int taskId) { List<Integer> toRemove; for (List<Integer> task : tasks) { if (task.get(1) == taskId) { toRemove = task; break; } } if (toRemove != null) { tasks.remove(toRemove); } } publicintexecTop() { if (tasks.isEmpty()) { return -1; } return tasks.poll().get(0); } }
答:因为 List<Integer> toRemove;是局部变量,局部变量系统不会自动初始化。且虽然在 for 循环中执行了赋值语句,但是编译器不确定for 循环以及 if 语句是否被执行,因此编译不通过。应提前初始化为 null,否则编译器会报错variable a might not have been initialized。