LocalDate 私有变量月日短数据类型
LocalDate private variables month and day short data type
在 LocalDate 的源代码中 class 我看到私有实例变量 month 和 day 是 shorts 而不是 ints.
This is the Docs of the LocalDate class.
** 一小部分源代码 **
private final int year;
private final short month;
private final short day;
private LocalDate(int year, int month, int dayOfMonth) {
this.year = year;
this.month = (short) month;
this.day = (short) dayOfMonth;
}
public int getDayOfYear() {
return getMonth().firstDayOfYear(isLeapYear()) + day - 1;
}
public int getMonthValue() {
return month;
}
public int getDayOfMonth() {
return day;
}
正如您在变量本身旁边看到的,int 数据类型用于月份和日期。为什么要缩短呢?
为什么不是这个?
private final short year;
private final byte month;
private final byte day;
一切都是关于 存储 。当你创建一个 LocalDate 的对象时,它会在堆中分配一些 space ,分配的堆大小取决于你拥有的实例变量的类型。这里因为 month 和 day 被声明为 'short',所以将为它们分配 2 个字节,如果声明为 int ,则每个为 4 个字节。
不管参数的类型,赋值的时候会自动从int装箱成short。
在 LocalDate 的源代码中 class 我看到私有实例变量 month 和 day 是 shorts 而不是 ints.
This is the Docs of the LocalDate class.
** 一小部分源代码 **
private final int year;
private final short month;
private final short day;
private LocalDate(int year, int month, int dayOfMonth) {
this.year = year;
this.month = (short) month;
this.day = (short) dayOfMonth;
}
public int getDayOfYear() {
return getMonth().firstDayOfYear(isLeapYear()) + day - 1;
}
public int getMonthValue() {
return month;
}
public int getDayOfMonth() {
return day;
}
正如您在变量本身旁边看到的,int 数据类型用于月份和日期。为什么要缩短呢?
为什么不是这个?
private final short year;
private final byte month;
private final byte day;
一切都是关于 存储 。当你创建一个 LocalDate 的对象时,它会在堆中分配一些 space ,分配的堆大小取决于你拥有的实例变量的类型。这里因为 month 和 day 被声明为 'short',所以将为它们分配 2 个字节,如果声明为 int ,则每个为 4 个字节。
不管参数的类型,赋值的时候会自动从int装箱成short。