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.)
Set
", butNULL
might also be appropriate depending on what you're doing. – DizzySet<E> = new HashSet<E>()
is one of the simplest. – Nosingjava.util.File.list()
. It returnsnull
if a file cannot provide its contained files (no set), or an empty array, if a file doesn't contain any files (empty set)... – Selah