Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java |= operator question [duplicate]

Tags:

java

operators

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;
}
like image 519
user452915 Avatar asked Sep 22 '10 10:09

user452915


2 Answers

It is a shorthand for:

result = result | add(e);

Where the | is the bitwise OR operator.

like image 66
Femaref Avatar answered Oct 06 '22 02:10

Femaref


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 seems 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 decide 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 a logical OR, except for booleans where the effect is basically the same, the only difference being the | does not have 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.

like image 43
Dave Webb Avatar answered Oct 06 '22 02:10

Dave Webb