why I have to write the first statement before calling bulk operation??
Set<Type> union = new HashSet<Type>(s1);
union.addAll(s2);
why I have to write the first statement before calling bulk operation??
Set<Type> union = new HashSet<Type>(s1);
union.addAll(s2);
One must instantiate an object before calling a method.
In this case, trying to call the addAll
method on a null
object will cause a NullPointerException
. Therefore, the Set
union
object must first be constructed somehow, then can it used in any meaningful way.
I think it would be a good idea to go over the given code and try to understand what the code is trying to accomplish.
Set<Type> union = new HashSet<Type>(s1);
union.addAll(s2);
The above code is tells me the following:
Let's make a new HashSet
from the existing elements of the Collection
s1
(which I assume to be something like another Set
.)
The newly created HashSet
will be stored as a Set
with the name union
-- the code seems to imply that this new Set
is going to represent some kind of union.
To the union
, elements from another Collection
(probably another Set
that is called s2
) will be added by the addAll
method.
Now, I think that the union
object contains an union of the Set
s s1
and s2
.
When writing code, one should pay attention to trying to tell others what the code intends to do. Having the code explain what it's doing is going to result in more readable and maintainable code that is going to make it easier (and possibly a pleasure) for others to read and understand.
I believe you don't need to copy another set, but you need to call the new operator. You could have:
Set<Type> union = new HashSet<Type>();
union.addAll(s2);
//and if you want s1 to be included too:
union.addAll(s1);
If you want to do this more elegantly, use the double brace initialization:
Set<Type> union = new HashSet<Type>() {{
addAll(s1);
addAll(s2);
}};
You can ensure a more optimal union if you declare the capacity of your union set to be the combined sizes of s1 and s2.
HashSet<Type> union = new HashSet<Type>(s1.size() + s2.size());
union.addAll( s1 );
union.addAll( s2 );
Furthermore, you can put this union code into a static method of another utility class so all your calling code is only one line
public abstract class Unionizer {
public static final HashSet<Type> union( HashSet<Type> s1, HashSet<Type> s2 ) {
HashSet<Type> union = new HashSet<Type>(s1.size() + s2.size());
union.addAll( s1 );
union.addAll( s2 );
return union;
}
}
Now everywhere you need to union two sets together you only need to type:
HashSet<Type> union = Unionizer.union( s1, s2 );