Does addAll() return false?

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.


|= 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.


From docs of addAll()

returns:

true if the collection changed as a result of the call.

If the collections not at all modified, then false.

Consider the below program.(follow the result in comments)

public static void main(String[] args) {
        List<String> l1= new ArrayList<String>();
        l1.add("test");
        List<String> l2= new ArrayList<String>();
        System.out.println(l2.addAll(l1));//true
        System.out.println(l2.addAll(l1));//true
        
        Set<String> s1= new HashSet<String>();
        s1.add("test");
        Set<String> s2= new HashSet<String>();
        System.out.println(s2.addAll(s1));//true
        System.out.println(s2.addAll(s1));//false
        }