我有以下Java方法:
private int calculate() {
return (bytes[0] & 0xff) + ((bytes[1] & 0xff) << 8);
}
Run Code Online (Sandbox Code Playgroud)
PMD对此代码抱怨"UselessParentheses"违规.
我已经审查了运算符优先级规则,但我仍然没有在该代码中看到冗余的括号.我错过了什么吗?
这段代码中没有不必要的括号,因为你可以看到你运行这个:
byte [] bytes = new byte[] {1,2};
System.out.println( (bytes[0] & 0xff) + ((bytes[1] & 0xff) << 8));
System.out.println( bytes[0] & 0xff + ((bytes[1] & 0xff) << 8));
System.out.println( (bytes[0] & 0xff) + (bytes[1] & 0xff) << 8);
System.out.println( (bytes[0] & 0xff) + (bytes[1] & 0xff << 8));
Run Code Online (Sandbox Code Playgroud)
此外,有时为了可读性添加额外的括号实际上是好的.例如:
int i = x << y + z; // this will shift x by y+z bits
int j = x << (y + z); // equivalent, but more readable
Run Code Online (Sandbox Code Playgroud)
在阅读了操作员的喜好,代码行和PMD警告之后,这很可能是少数情况下的优先级之一,优先级应像
PMD complains on this code with a useless (parenthesis warning)
Run Code Online (Sandbox Code Playgroud)
而不是
PMD complains on this code with a (useless parenthesis) warning.
Run Code Online (Sandbox Code Playgroud)
您的代码是正确的,并且括号也不是多余的。删除它们会降低代码的可读性,并且每一个都需要。实际上,这整个问题值得一部xkcd漫画