I want to declare a generic class that will work on triplets - key
, value
and metadata
.
The key
and value
fields are mandatory but the metadata
field is optional.
class Triplet<K,V,M>{
K key;
V value;
M metadata;
//setters and getters
}
While using the above class I have to initialize it like below -
Triplet<Integer, String, String> t1 = new Triplet<>();
// Setters
But for some use cases metadata
is optional. So when I use null
as the 3rd type argument, the compiler gives an error -
Triplet<Integer, String, null> t2 = new Triplet<>();
How should I correctly instantiate a parameterized type that works for multiple types, where one of the type arguments specified at the use-site is optional?
You can use Void
e.g.
Triplet<Integer, String, Void> t2 = new Triplet<>();
I would argue that if you determine that the third parameter is not present (as intended by using null
), then it's no longer a triplet, but a pair. Just keep things simple and use a Pair
class instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With