关于这段Java代码的问题,为什么这么写

Questions about this bit of Java code, why it is written as it is

我看到了这个源代码,想确保我理解为什么它是这样写的(或者如果应该这样写):

boolean modified = false;
Set<String> possibleSites = settings.getPossibleSites();
Set<String> visibleSites = settings.getVisibleSites();
modified = someMysteriousMethod();

// Remove sites from visibleSites that are not in possibleSites
modified |= visibleSites.retainAll(possibleSites);

我对 LAST 语句的问题:

  1. 为什么要用位运算符? retainAll() 将 return 一个关于发生了什么的布尔值?

  2. operator/statement 说的是什么?如果 modified 等于 return 值,则单独保留 modified 的值,或者如果 return 值不同,则将 modified 设置为新值?

意思是如果modifiedretainAll()为真,那么modified应该为真。 (根据名称,这很有意义。如果 Set 已更改,retainAll 仅 return 为真,而 someMysteriousMethod 可能 return 为真或假,具体取决于Set 的状态已更改。)

代码分解为:

modified = modified | visibleSites.retainAll(possibleSites);

查看以下代码以查看布尔值 | 的结果:

System.out.println(true|true);
System.out.println(false|true);
System.out.println(true|false);
System.out.println(false|false);

输出:

true
true
true
false

(只有false|false会returnfalse,所以在代码中,modifiedretainAll都必须return false modifiedfalse)

boolean retainAll(Collection<?> c)

returns true 如果 the set changed as a result of the call

modified |= visibleSites.retainAll(possibleSites);

所以上面的语句意味着,if modified is true OR retainAll returns true,则modified设置为true,否则modified的值为false

retainAll method in Set 的 return 值表示集合是否被调用更改。

Returns:

true if this set changed as a result of the call

这里,true表示集合被修改了。 |= 复合运算符对参数执行“或”并将其分配回左侧。对于你的情况,这意味着如果 retainAll returns true,则将 true 分配回 modified,否则保持 modified 不变。

根据 javadoc,

retainAll retuns true if this set changed as a result of the call

a |= b是影响“a or b”结果为a的操作。 因此,在您的情况下,想法是影响 modified 语句“visibleSitesOR visibleSitesretainAll 修改之前修改”的结果

在此之后:

modified = someMysteriousMethod();

那么modified可能是对的,也可能不是。以下影响

modified |= visibleSites.retainAll(possibleSites);

是让 modified 如果已经为真,则设置为真,如果其他条件成立,则将其从假更改为真(我说 effect 是故意的,我不是在描述实际的指令操作)。

第二个语句可以写成

if (visibleSites.retainAll(possibleSites)) {
      modified = true;
}

同样的结果。在某种程度上,这是一个品味问题。我发现原文(使用 |= 运算符)更易读,因为它是一个简单的直线逻辑表达式而不是控制流语句

顺便说一句,它不叫 'bitwise' 运算符。 Java 有两个 '|'和两个相应的“|=”运算符;在整数之间是 bitwise-or, between booleans it's logical-or.