How to implement an empty set - โˆ…?

Assuming you want to implement set theory concepts such as element , set , collection and relation in Java: how would you represent an empty set โˆ… ?

Am I fooling myself if I think about the concept of NULL , since it is used by three-valued database logic?

+8
java null set-theory
source share
2 answers

Use Collections.emptySet():

Returns an empty set (immutable). This set is serializable. Unlike a field with a named name, this method is parameterized. This example illustrates a safe type for getting an empty set:

  Set<String> s = Collections.emptySet(); 

Implementation note: implementations of this method do not need to create a separate Set object for each call. Using this method is likely to be of comparable value for using a field with a named name. (Unlike this method, the field does not provide type safety.)

+27
source share

Using null to represent an empty set is a bad idea . A null does not behave like a Set , because (obviously) all attempts to perform an operation on it will throw a NullPointerException . This means that if you use null to indicate an empty set, you will be clogged with tests for null ... and if you skip one, you will get an error.

The solution is to use Collections.emptySet () if you want an immutable empty set, or create an instance of the corresponding Set class if you want the modified set to start from empty.

+8
source share

All Articles