Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a basic Java Set implementation that does not permit nulls?

Tags:

java

null

set

api

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 nulls, 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.

like image 279
Aaron K Avatar asked Feb 26 '09 15:02

Aaron K


People also ask

Which set does not allow null?

Null values in TreeSet − The TreeSet object doesn't allows null values but, If you try to add them, a runtime exception will be generated at.

Which Java collection does not allow null?

Hashtable does not allow any null as key or value, and Hashtable is legacy and only single thread can access at a time.

Does set permits null values in Java?

No, Set Interface do allow null value only its implementation i.e. TreeSet doesn't allow null value. even though you have not written iteration code and have only oTreeSet. add(null) in your code it compiles and at runtime it throws NullPointerException.

Which of collections does not permit null elements?

NullPointerException - if the specified collection contains one or more null elements and this collection does not permit null elements (optional), or if the specified collection is null.


1 Answers

Better than extending a particular implementation, you can easily write a proxy implementation of Set that checks for nulls. This analogous to Collections.checkedSet. Other than being applicable to any implementation, you can also be sure that you have overridden all applicable methods. Many flaws have been found by extending concrete collections which then have additional methods added in later versions.

like image 86
Tom Hawtin - tackline Avatar answered Sep 24 '22 06:09

Tom Hawtin - tackline