-
Couldn't load subscription status.
- Fork 11.1k
LivingWithNullHostileCollections
Colin Decker edited this page Oct 17, 2017
·
4 revisions
Many JDK collection types permit null elements:
ArrayListLinkedListHash{Set,Map}LinkedHash{Set,Map}-
Tree{Set,Map}(with suitable comparator) IdentityHashMap-
EnumMap(values) CopyOnWriteArray{List,Set}
But many don't:
EnumSet-
EnumMap(keys) ConcurrentHashMapConcurrentSkipList{Set,Map}- All ten
Queueimplementations exceptLinkedList
Likewise in Guava we have many general-purpose collections that permit null:
ArrayListMultimapHashBiMapHashMulti{set,map}LinkedHashMulti{set,map}-
TreeMulti{set,map}(with suitable comparator) LinkedListMultimapMutableClassToInstanceMapHashBasedTableSets.union/intersection/difference
but many that do not:
ConcurrentHashMultisetEnumBiMapEnumMultisetMinMaxPriorityQueueInterners-
MapMaker-made maps Sets.cartesianProduct/powerSet- All implementations of
ImmutableCollectionandImmutableMap
What if you find yourself wanting to put a null element into one of these null-hostile beasts?
- If in a Set or as a key in a Map -- don't; it's clearer (less surprising) if you explicitly special-case null during lookup operations
- If as a value in a Map -- leave out that entry; keep a separate Set of non-null keys (or null keys)
- If in a List -- if the list is sparse, might you rather use a
Map<Integer, E>? - Consider if there is a natural "null object" that can be used. There isn't
always. But sometimes.
- example: if it's an enum, add a constant to mean whatever you're expecting null to mean here.
- Just use a different collection implementation, for example
Collections.unmodifiableList(Lists.newArrayList())instead ofImmutableList. - Mask the nulls (this needs more detail)
- Use
Optional<T>
See also: using and avoiding null.
- Introduction
- Basic Utilities
- Collections
- Graphs
- Caches
- Functional Idioms
- Concurrency
- Strings
- Networking
- Primitives
- Ranges
- I/O
- Hashing
- EventBus
- Math
- Reflection
- Releases
- Tips
- Glossary
- Mailing List
- Stack Overflow
- Android Overview
- Footprint of JDK/Guava data structures