2

In the source code of the LocalDate class I saw that the private instance variables month and day were shorts instead of ints.

This is the Docs of the LocalDate class.

** A short part of the source code **

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;
}

As you can see beside the variables themselve, the int data type is used for month and day. Why make it a short then?
And why not this?

private final short year;
private final byte month;
private final byte day;
4

1 回答 1

2

Its all about the storage. When you create an object of LocalDate, it allocates some space in heap, the size of heap allocated is based on the type of instance variables you have. Here since month and day are declared as 'short', 2 byte will be allocated for them, if it was declared as int , it will be 4 bytes each.

It doesn't matter the type of parameters, it will be automatically boxed to short from int when you assign the value.

于 2016-12-07T11:44:25.243 回答