← 中文资源

简体中文版本

方法体内的局部 record

在方法体内声明的局部 record 既能携带字段也能定义方法并参与排序:中间结果就地建模,不扩大类级别的 API 面,方法外无法引用。

阅读英文原文

实现说明

底层就是类 LocalRecordInMethod、ChannelRevenue和函数 main。 本示例的循环部分是 for (int i = 0; i < channels.size(); i++)。

使用要点

  • 跑完文件,输出里会留下标记——channel:、best =。

常见问题

运行「方法体内的局部 record」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 channel:、best = 标签标明各步骤。

核心语句

rows.sort(Comparator.comparingInt(ChannelRevenue::cents).reversed());
double dollars() { return cents / 100.0; }

代码示例

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class LocalRecordInMethod {

    public static void main(String[] args) {
        List<String> channels = List.of("web", "mobile", "api");
        int[] revenue = { 4800, 3100, 900 };

        // 局部 record:字段、方法都可用,只在方法体内可见
        record ChannelRevenue(String channel, int cents) {
            double dollars() { return cents / 100.0; }
        }

        List<ChannelRevenue> rows = new ArrayList<>();
        for (int i = 0; i < channels.size(); i++) {
            rows.add(new ChannelRevenue(channels.get(i), revenue[i]));
        }
        rows.sort(Comparator.comparingInt(ChannelRevenue::cents).reversed());
        rows.forEach(r -> System.out.println("channel: " + r.channel() + " $" + r.dollars()));

        ChannelRevenue best = rows.get(0);
        System.out.println("best = " + best.channel() + " $" + best.dollars());
    }
}