I'm looking for a class from the Java Collection Framework that would not allow null elements.
Do you know one?
I'm looking for a class from the Java Collection Framework that would not allow null elements.
Do you know one?
Most Queue
implementations (with the notable exception of LinkedList
) don't accept null
.
EnumSet
is a special-purpose Set
implementation that doesn't allow null
values.
Use Constraints
:
import com.google.common.collect.Constraints;
...
Constraints.constrainedList(new ArrayList(), Constraints.notNull())
from Guava for maximum flexibility.
UPDATE: Guava Constraints has been deprecated in Release 15 - apparently without replacement.
UPDATE 2: As of now (Guava 19.0-rc2) Constrains is still there and not deprecated anymore. However, it's missing from the Javadoc.
I'm afraid that the Javadoc is right as MapConstraint
have been deprecated in Release 19, too
There's a roundup of such collections here.
Apache Commons Framework - CollectionUtils.addIgnoreNull
Adds to myList if myObj is not null.
org.apache.commons.collections.CollectionUtils.addIgnoreNull(myList, myObj)
Using Google Guava Predicates (the answer from @Joachim Sauer is deprecated)
//list is the variable where we want to remove null elements
List nullRemovedList=Lists.newArrayList(Iterables.filter(list, Predicates.notNull()));
//Or convert to Immutable list
List nullRemovedList2=ImmutableList.copyOf(Iterables.filter(list, Predicates.notNull()));
Hashtable does not allow null keys or values.
Start here, the Collections API Page. Check out the "See Also" section. Follow the links. The decision to allow or disallow null is made by the implementing class; just follow the links in the various "See Also" sections to get to the implementing classes (for example, HashMap) then look at the insertion methods (generally a variation on add, push, or put) to see if that implementation permits null.