实现说明
真正干活的是类 SlotRegistry和函数 main,其余都是接线。
使用要点
- 演示输出是带标签的(
first in:、second in:、after:),每个操作都会留下自己的一行标注。
常见问题
运行「Map 的 putIfAbsent 与 computeIfPresent」会打印什么?
整个文件跑完,输出行以 first in:、second in:、after: 这类前缀开头。
核心语句
String bumped = slots.computeIfPresent("worker-a", (k, v) -> v + "-retried");
Map<String, String> slots = new HashMap<>();
代码示例
import java.util.HashMap;
import java.util.Map;
public class SlotRegistry {
public static void main(String[] args) {
Map<String, String> slots = new HashMap<>();
// putIfAbsent:键缺席才写入;已有值原样保留,不覆盖
System.out.println("first in: " + slots.putIfAbsent("worker-a", "job-1"));
System.out.println("second in: " + slots.putIfAbsent("worker-a", "job-2"));
System.out.println("after: " + slots);
// computeIfPresent:只在键存在时改写,缺席则返回 null 而不报错
String bumped = slots.computeIfPresent("worker-a", (k, v) -> v + "-retried");
System.out.println("bumped: " + bumped);
System.out.println("missing: " + slots.computeIfPresent("worker-x", (k, v) -> "never"));
// 两者配合:占用用 putIfAbsent,重试用 computeIfPresent,读写路径互不越界
System.out.println("final: " + slots);
}
}