1

example:

public class Something {
    private Set<String> names = new HashSet();

    public void add(String n) { names.add(n); }
    public void add(Set<String> set) { names.addAll(set); }
}

But, I am curious why AbstractCollection.add(E e) is not overloaded in the same way I overload my Something.add(String n). Why is there the distinct AbstractCollection.addAll(Collection<? extends E> c)?

I can't imagine it makes any practical difference.
So, my conclusion is to only overload when there is strong, logical, reason to do so. Overloading just because I can is discouraged?

3

As @MetaFight points out, add and addAll have different semantics. But there is also a historical perspective to the Collection API design.

The Collections framework was added to Java before it supported generic types. In those days, the API for Collection defined the methods as follows:

   boolean add(Object e)          // adds a single element

   boolean addAll(Collection c)   // adds all elements in the collection

Now imagine they had instead designed the API like this:

   boolean add(Object e)          // adds a single element

   boolean add(Collection c)      // adds all elements in the collection

and someone wrote this:

   List list = new ArrayList();
   Object list2 = new ArrayList();
   List list3 = new ArrayList();
   list3.add(list);
   list3.add(list2);

Question: What would list3 now contain? Answer: one empty list.

Confusing ... isn't it! But this neatly illustrates the danger of having overloads do substantially different things.

Now from Java 5, you would (should) declare the lists with parameterized types (not raw types) and the above (hypothetical) example would most likely give you compilation errors. But, remember, Collections were introduced a few years before generic types. Even if they had wanted to rename addAll as an overload of add, they couldn't have done this without breaking binary compatibility.


I can't imagine it makes any practical difference.

It does. See example above ... for an illustration of the general principle.

So, my conclusion is to only overload when there is strong, logical, reason to do so. Overloading just because I can is discouraged?

Yes, and Yes. But also, you should only overload when the methods do essentially the same thing.

1

It's because add and addlAll have different meanings.

add is for adding a single item to the collection.

addAll is for adding multiple items to the collection.

Since both methods means something different it makes sense to give them distinct names.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.