Muno
Muno

Reputation: 585

Why doesn't addAll() support the addition of a collection's copy to the collection?

In a method, I make two calls. The first call constructs and returns a hashset from another method. The second call adds this newly constructed set to an existing one, passed in as a parameter to this method.

public static void someMethod(java.util.HashSet<Coordinate> invalidPositions)
{
    java.util.HashSet<Coordinate> newSet = SomeClass.getInvalidPositions(x, y);
    invalidPositions.addAll(newSet);
}

Often times, the passed in set, the pre-existing one, will add another set whose contents are the same as itself! That is, setOne.equals(setTwo) == true

Instead of adding the other set, however, the JavaDocs say of addAll():

public boolean addAll(Collection c)

Adds all of the elements in the specified collection to this collection (optional operation). The behavior of this operation is undefined if the specified collection is modified while the operation is in progress. (This implies that the behavior of this call is undefined if the specified collection is this collection, and this collection is nonempty.)

Have I understood this correctly? If two sets are equal, java will not support one's addition of the other? If this is true, is there any reason to design the language in this way?

Upvotes: 2

Views: 1279

Answers (1)

Cinnam
Cinnam

Reputation: 1922

a.equals(b) is different from a == b.

What the javadoc means is that the behavior is undefined if you do a.addAll(a). There is no problem in doing a.addAll(b) as long as they are different instances.

Upvotes: 6

Related Questions