Search code examples
javaoperators

Java |= operator question


I need help about this strange operator |=. Can you explain to me what this code does ?

@Override
public boolean addAll(Collection<? extends E> c) {
    boolean result = false;
    for (E e : c) {
        result |= add(e);
    }
    return result;
}

Solution

  • The code is adding all members of a Collection using the add() method which returns a boolean, indicating if the add() succeeded or not. What the addAll method does is return true if any of the adds succeeded and false if all of them failed. (This does seem odd to me, since I'd only return true if all the adds were succesful, but I digress.)

    So you could do it like this:

    @Override
    public boolean addAll(Collection<? extends E> c) {
        boolean result = false;
        for (E e : c) {
            if (add(e)) {
               result = true;
            }
        }
        return result;
    }
    

    But that's a little verbose as you can act on the result variable more directly:

    @Override
    public boolean addAll(Collection<? extends E> c) {
        boolean result = false;
        for (E e : c) {
            result = add(e) || result;
        }
        return result;
    }
    

    So we're logically OR-ing the old value of result with the return value of add to get the new value. (Note: we want result to be on the right hand side of the ||; this is because || "shortcircuits" and doesn't bother checking the right hand side of an || if the left side is true). So if add(e) and result were the other way around, it would not evaluate the right hand side — i.e. not run the add() method — once result were true.)

    Whoever wrote that method decided they wanted to be as terse as possible so they changed:

    result = add(e) || result;
    

    to:

    result |= add(e);
    

    which is the same as:

    result = result | add(e);
    

    The | operator is a bitwise OR which is not the same as a logical OR, except for booleans where the effect is basically the same, the only difference being the | not having the shortcircuit behaviour mentioned above.

    There is no ||= syntax in Java which is why the bitwise OR is being used, although even if it did, it would probably have the same shortcircuit problem mentioned above.