0

I've lately bumped in something weird. Consider the following method:

public boolean addAll(Collection<T> col) {
    boolean added = false;

    for(T t : col)
        added |= add(t);

    return added;
}

Although I understand what this wants to do, that's - not change it to false, if it exceeded at least once (if a later element failed). But what does this actually mean. How is it read. And are there any similar gadgets in boolean?

Mordechai
  • 15,437
  • 2
  • 41
  • 82

2 Answers2

2

The |= operator is equivalent to this:

added = ( added | add(t) );
jahroy
  • 22,322
  • 9
  • 59
  • 108
2

It is a bitwise-or combined with an equals.

As such, if it has been set to true (i.e. 1) before, if you bitwise or either a true or false (1 or 0) with it, you'll always return true (1) as 0 OR 1 = 1 and 1 OR 1 = 1.

It is in effect the same as:

added = (added | add(t));
Quetzalcoatl
  • 3,037
  • 2
  • 18
  • 27
  • 3
    @MouseEvent: Not sure if that's valid, but even if it is, `||` is lazy-evaluated which means that if the left value is already true, then the `add()` function won't be called – mpen Apr 04 '13 at 22:46
  • That is a logical OR, which behaves differently to a bitwise OR. See: http://stackoverflow.com/questions/4014535/differences-in-boolean-operators-vs-and-vs – Quetzalcoatl Apr 04 '13 at 22:46
  • @Mark: Indeed it is lazily evaluated, the logical OR will short circuit whereas the bitwise OR will not. – Quetzalcoatl Apr 04 '13 at 22:48
  • @MouseEvent `||=` is not a valid operator. – assylias Apr 04 '13 at 22:49
  • I knew about bitwise operators, but never knew that booleans works this way too... – Mordechai Apr 04 '13 at 22:58
  • In Java, there is no special relationship between `true` and `1` – Steve Kuo Apr 04 '13 at 23:49
  • I was merely utilizing the effective similarity between `1` and `0` and `true` and `false`, since we're talking bitwise here I felt it would help with the explanation. – Quetzalcoatl Apr 05 '13 at 08:55