I need to distinguish between a property having a null value, and a property not existing at all. I could use a map, but for performance reasons, I am trying to use a fixed size array.
In the array, I could use null to indicate when a property does not exist at all. But, for a property that does exist and is null valued, is there a standard way to represent it in an array?
I thought of keeping a static member, e.g.
class MyClass {
private static final Object NULL = new Object(); // null wrapper
private Object[] m_arr = new Object[10];
// 'i' represents the index of a property in the array
boolean exists(int i) {
return m_arr[i] != null;
}
Object value(int i) {
if( !exists(i) ) throw new NullPointerException(); // does not exist
if( m_arr[i] == NULL ) return null;
// ... handling for other data types ...
}
}
Another possibility for representing null might be an enum?
class MyClass {
...
enum Holder {
NULL
}
...
// to check for a null value use m_arr[i] == Holder.NULL
}
NO... but, Java now has Optional which could be viewed as the same. You could also create a class to represent a null object, which can be done following the "Null Object Pattern". I wrote about this in a blog: https://www.professorfontanez.com/2020/04/the-beauty-of-null-object-pattern.html
Use Optional, eg
private Optional<String> myField;
There are three states. Here's how to handle them:
myfield = Optional.of("foo"); // attribute has non-null value
myfield = Optional.empty(); // attribute is present, but null
myfield = null; // attribute is not present
Jackson (ie Spring boot) json deserialization supports this out of the box, which is very handy for handling PATCH methods that require the distinction between a json key being specified but null and not specified.
Apache commons ObjectUtils has a NULL field for this purpose, if you don't want to define your own.
Does Java have a wrapper type for Null?
No.
But how I'd solve this problem means you don't need to a wrapper: just maintain a set of the indices which represent "explicit" null values.
class MyClass {
private Object[] m_arr = new Object[10];
private Set<Integer> presentButNullIndices = new HashSet<>();
// 'i' represents the index of a property in the array
Object value(int i) {
if (m_arr[i] == null && !presentButNullIndices.contains(i)) {
throw new NullPointerException();
}
// ... handling for other data types ...
}
// just an example of how to maintain the set
void insert(int i, Object value) {
if (value == null) {
presentButNullIndices.add(i);
}
else {
presentButNullIndices.remove(i);
}
m_arr[i] = value;
}
}
Worst case, the space complexity doubles, but that's only for clients which make heavy use of null values. contains on a set is O(1)
I'd also consider just prohibiting null values in the first place. Some map implementations do that and I've never found myself in a situation where I wish they didn't.