Java 8 是闰年实现。逻辑运算符是什么意思?

标签 java api java-8

我正在研究 Date API 的 java 8 实现并发现了这个

Checks if the year is a leap year, according to the ISO proleptic calendar system rules.

This method applies the current rules for leap years across the whole time-line. In general, a year is a leap year if it is divisible by four without remainder. However, years divisible by 100, are not leap years, with the exception of years divisible by 400 which are.

For example, 1904 is a leap year it is divisible by 4. 1900 was not a leap year as it is divisible by 100, however 2000 was a leap year as it is divisible by 400.

The calculation is proleptic - applying the same rules into the far future and far past. This is historically inaccurate, but is correct for the ISO-8601 standard.

public boolean isLeapYear(long prolepticYear) {
        return ((prolepticYear & 3) == 0) && ((prolepticYear % 100) != 0 || (prolepticYear % 400) == 0);
    } 

But give us prolepticYear & 3.

11111001111
    &
00000000011
00000000011

prolepticYear & 3 是什么意思。

最佳答案

prolepticYear & 3 让我们稍微改变一下。 3 在二进制中是11。因此,只有当 prolepticYear 的最后两位为零时,prolepticYear & 11 才会为零。 (这实际上称为位掩码)。

现在想想也有点不同:

 0100 - (4 in decimal, has last two bits zero)
 1000 - (8 in decimal, has last two bits zero)
 1100 - (12 in decimal, has last two bits zero)

 ... these are numbers divisible by four

通常 & 操作比 % 快。

有时 & 也用于其他目的(% 运算可能产生负数,而 & 会不是 - 这就是 HashMap 中的桶是如何根据 Key#hashcode可能负值来选择的,但这里不是这种情况)

关于Java 8 是闰年实现。逻辑运算符是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45165492/

相关文章:

php - 我的PHP获取YouTube视频API函数未打印任何内容

Android Google maps v2 错误同时膨胀 fragment

java - 如何在ubuntu 14.04中安装32位系统的eclipse neon版本

java - 在非 MACOS JRE 上捕获 java.lang.NoClassDefFoundError

java - 从 ZoneDdateTime 转换日期给出本地时间而不是 ZonedTime

java - 将数据从 Controller 传递到服务层时的 Autowiring 依赖关系

java - 在 JTable 中设置列​​标题

java - AWS API Gateway 自定义授权方。如何在 lambda 中访问 principalId

java - 更新记录 if somcolumn! ="somevalue",使用 Hibernate saveorupdate()

javascript - 如何限制可拖动区域?它在顶部和左侧起作用,但在右侧和底部不起作用