The API for the Java Set interface states:
For example, some implementations prohibit
null
elements and some have restrictions on the types of their elements
I am looking for a basic Set implementation that does not require ordering (as ArrayList provides for the List interface) and that does not permit null
. TreeSet, HashSet, and LinkedHashSet all allow null elements. Additionally, TreeSet has the requirement that elements implement Comparable.
It seems that no such basic Set
exists currently. Does anyone know why? Or if one does exist where I can find it?
[Edit]: I do not want to allow null
s, because later in the code my class will iterate over all elements in the collection and call a specific method. (I'm actually using HashSet<MyRandomObject
>). I would rather fail fast than fail later or accidentally incur some bizarre behavior due to a null
being in the set.
This is a failry general purpose way of doing it - you provide a Filter implementation that can restrict what gets added in whatevber way you want. Take a look at the source for java.util.Collections for ideas on the wrapping (I think my implementaiton of the FilteredCollection class is correct... but it is not extensivly tested). There is a sample program at the end that shows the usage.
You could easily write your own, by subclassing an appropriate existing class, and overriding all relevant methods so that you can't add
null
elements.BTW, if you'd asked for a
Map
implementation that does not allow nulls, the oldjava.util.Hashtable
does not.In this particular question/example surely if you have a
HashSet<MyRandomObject> mySet
callmySet.remove(null)
before starting the iteration over all elements you mentioned?There is no basic proprietary Set implementation that ignores or constrains null! There is EnumSet, but that one is tailors for the containment of enum types.
However, creating your own implementation can be avoided, if you use either Guava or Commons Collections:
1. Guava Solution:
2. Commons Collections:
Instead of checking
null
, every time, we can simply remove the null once before iterating over the set.You can remove the null values using
set.remove(null);
Output