Java – Non-null alternative to Void (Java unit type)

java

I have a map-like type SmurfMap<K, V> which in certain contexts I use as a set-like SmurfMap<K, Void>. Implementation details forbid the values of the map from being null, so I cannot actually use Void as a unit type. Are there any non-null alternatives to Void in the JCL or Guava?

Types considered and not yet rejected:

  • new singleton enum Unit
  • Class<Void>
  • TypeToken<Void>
  • Object

EDIT SmurfMap<K, V> does not implement java.util.Map. The datastructure backing a SmurfMap is terabytes to petabytes in size.

Best Answer

If you don't need the values, don't use a map. Use a Set. It's a collection that contains no duplicate elements (by equals and hashCode) and has O(1) membership checking.

If the code is impossible to structure in a way that uses a set, and it must use a map*, then of these options I'd make a singleton Unit type. I'd pick this because as a map value, it does the best job communicating that the value is unused. A Map<T, Boolean> implies that the boolean-ness of the values matters and should be checked.

* This indicates a pretty nasty code smell, and you should examine your design more.