I am creating a specialist tree collection and would like to have NIL
nodes instead of null
references. As a contrived example:
public interface Value<V> {
boolean hasValue(V value);
}
public class Node<V> implements Value<V> {
private static final Value<V> NIL = new Value() {
public boolean hasValue(V value) {
return false;
}
}
private Value<V> next = NIL;
private V value;
public boolean hasValue(V value) {
return this.value.equals(value) || next.hasValue(value);
}
}
I realise this code is illegal because the static member NIL
is using the generic type V
. There is a good explanation of why in java static class Singleton with generic However that highlights that there needs to be a single instance irrespective of type. That will work fine in my case: the behaviour of NIL
is identical.
There are some simple workarounds in this case but in the use case I'm working on there are several variants of NIL
each of which overrides behaviour in the interface.
I could make NIL
a separate class and create a new instance rather than using a constant but I am dealing with a very large collection and don't want the overhead of many objects that don't actually hold any state.
Is there an elegant way to have a single constant object while retaining the ability to override methods which use the generic type? If not, is there an alternate design that achieves the same outcome?