How to workaround this JDK limitation?

2019-01-11 06:25发布

问题:

I'm looking for a class from the Java Collection Framework that would not allow null elements.

Do you know one?

回答1:

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.



回答2:

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



回答3:

There's a roundup of such collections here.



回答4:

Apache Commons Framework - CollectionUtils.addIgnoreNull

Adds to myList if myObj is not null.

org.apache.commons.collections.CollectionUtils.addIgnoreNull(myList, myObj)



回答5:

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()));


回答6:

Hashtable does not allow null keys or values.



回答7:

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.