Search code examples
javasetbitwise-or

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


I came across this source code and wanted to make sure I understood why it is written as it is ( or if it should be ):

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

My questions about the LAST statement:

  1. Why use the bitwise operator? retainAll() will return a boolean as to what happened?

  2. What is the operator/statement saying? If modified equals the return value leave the value of modified alone OR if the return value is different set modified to that new value?


Solution

  • boolean retainAll(Collection<?> c)
    

    returns true if the set changed as a result of the call

    modified |= visibleSites.retainAll(possibleSites);
    

    So the above statement means, if modified is true OR retainAll returns true, then modified is set to true, otherwise the value of modified is false