Record
简介
在 Java 16 中有一个新的 record 关键字用于生成 record 类。
简单使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| public final class Range { private final int start; private final int end;
public Range(int start, int end) { this.start = start; this.end = end; }
public int start() { return start; }
public int end() { return end; }
@Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj == null || obj.getClass() != this.getClass()) { return false; } var that = (Range) obj; return this.start == that.start && this.end == that.end; }
@Override public int hashCode() { return Objects.hash(start, end); }
@Override public String toString() { return "Range[" + "start=" + start + ", " + "end=" + end + ']'; }
}
|
等同于
public record Range(int start, int end) {
public Range{
// 参数检查
}
}```