38

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

Do you know one?

Stephan
  • 41,764
  • 65
  • 238
  • 329
  • 2
    What should happen? If you just want to ignore list.add(null) I would make a subclass of your favourite implementation, overwrite add() and check for null value – leifg Aug 09 '11 at 13:50
  • Perhaps the better way to do it is to never insert nulls in the first place? Tolerating (and thus guarding against) nulls is usually a poor practice. – Konrad Garus Aug 09 '11 at 13:51
  • 6
    @leifg Don't just overwrite add but also addAll! Otherwise you may be in for an interesting surprise. – Voo Aug 09 '11 at 14:35

7 Answers7

47

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

Community
  • 1
  • 1
maaartinus
  • 44,714
  • 32
  • 161
  • 320
20

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.

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
12

Apache Commons Framework - CollectionUtils.addIgnoreNull

Adds to myList if myObj is not null.

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

Cengiz
  • 5,375
  • 6
  • 52
  • 77
12

There's a roundup of such collections here.

Kevin Bourrillion
  • 40,336
  • 12
  • 74
  • 87
4

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()));
Didac Montero
  • 2,046
  • 19
  • 27
1

Hashtable does not allow null keys or values.

Steve B.
  • 55,454
  • 12
  • 93
  • 132
  • 7
    my goodness, that's a blast from the past! It isn't even a `Collection`, never mind a `List`. – fommil Oct 03 '12 at 17:51
1

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.

DwB
  • 37,124
  • 11
  • 56
  • 82