Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does addAll() return false?

While looking at the source code of CollectionUtils addAll method. I notice it uses |= symbol

public static <T> boolean addAll(Collection<? super T> c, T... elements) {
 boolean result = false;
 for (T element : elements)
    result |= c.add(element);

 return result;
}

From my understanding |= is a bitwise or operator and just a shorthand of result = result|c.add(element), so for example :

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

This means that if any item successfully added, it will return true. Now I've been wondering is there will be an instance, it will return false? If not why it has a return?

like image 497
Ken de Guzman Avatar asked Oct 01 '14 09:10

Ken de Guzman


2 Answers

If all the elements to be added were already in the Collection (prior to the call to addAll), and the Collection doesn't allow duplicates, it will return false, since all the individual add method calls would return false. This is true for Collections such as Set.

For other Collections, add always returns true, and therefore addAll would return true, unless you call it with an empty list of elements to be added.

like image 183
Eran Avatar answered Sep 22 '22 14:09

Eran


|= is bitwise OR

| (Bitwise OR) sets a bit to 1 if one or both of the corresponding bits in its operands are 1, and to 0 if both of the corresponding bits are 0. In other words, | returns one in all cases except where the corresponding bits of both operands are zero. The resulting bit pattern is the "set" (1 or true) bits of any of the two operands. This property is used to "set" or "turn on" a "flag" (bit set to one) in your flags or options variable regardless of whether that flag was set previously or not. Multiple flag bits can be set if a combo MASK is defined.

// To set or turn on a flag bit(s)
flags = flags | MASK;
// or, more succintly
flags |= MASK;

So your code is equivalent to:

boolean result = false;
for (T element : elements){
   result = result | c.add(element);
}
return result;

Initially result will be false and as one of elements successfully get added to collection will be set to true i.e c.add(element);. So it will return true if one of elements get added.

like image 28
Zaheer Ahmed Avatar answered Sep 22 '22 14:09

Zaheer Ahmed