Alex Rivera | Logout

How to implement the empty set - ∅?

Asked 2012-07-10T13:34:02.710
29

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?

Edit
Report

1 Answer

16

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.)

answered 2012-07-10T14:53:16.887

Your Answer