Reputation: 371
Assuming that you want to implement set theory concepts such as element
, set
, collection
and relation
in Java: How would you represent the empty set ∅
?
Do I mislead myself, if I think of the NULL
concept as it is used by the three-valued logic of databases?
Upvotes: 28
Views: 53374
Reputation: 719386
Using null
to represent an empty set is a bad idea. A null
doesn't behave like a Set
because (obviously) all attempts to perform an operation on it will throw a NullPointerException
. That means that if you use null
to denote an empty set, you code will be littered with tests for null
... and if you miss one, you've got a bug.
The practical solution is to use Collections.emptySet()
if you want an immutable empty set, or create an instance of the appropriate Set
class (e.g. new HashSet<>()
) if you want a mutable set that starts out empty.
On rereading the question, I realize that you may have meant something different to my original understanding.
If you were trying to implement / model mathematical set theory concepts in Java from scratch, you would probably implement Set
as an immutable class. (In mathematics, you don't mutate things!) The empty set is then just a Set
instance with no elements in it. No special handling required.
The NULL
concept is not required ... unless you are specifically trying to incorporate a "null", "undefined sets" or some similar concept in your mathematical model of sets. (If you are, I'm not sure we can advise you without understanding your model ... from a mathematical perspective.)
Upvotes: 16
Reputation: 5745
Returns the empty set (immutable). This set is serializable. Unlike the like-named field, this method is parameterized. This example illustrates the type-safe way to obtain an empty set:
Set<String> s = Collections.emptySet();
Implementation note: Implementations of this method need not create a separate Set object for each call. Using this method is likely to have comparable cost to using the like-named field. (Unlike this method, the field does not provide type safety.)
Upvotes: 55