英文:
Optional generic type argument
问题
我想声明一个通用类,该类将用于三元组 - key、value 和 metadata。
key 和 value 字段是必需的,但 metadata 字段是可选的。
class Triplet<K, V, M> {
K key;
V value;
M metadata;
//setters and getters
}
在使用上述类时,我必须像下面这样初始化它 -
Triplet<Integer, String, String> t1 = new Triplet<>();
// 设置器
但是对于某些用例,metadata 是可选的。因此,当我将第三个类型参数指定为 null 时,编译器会报错 -
Triplet<Integer, String, null> t2 = new Triplet<>();
在哪种情况下,我应该正确实例化一个参数化类型,该类型适用于多种类型,其中在使用点指定的一个类型参数是可选的?
英文:
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?
答案1
得分: 9
你可以使用 Void,例如:
Triplet<Integer, String, Void> t2 = new Triplet<>();
英文:
You can use Void e.g.
Triplet<Integer, String, Void> t2 = new Triplet<>();
答案2
得分: 5
我认为,如果您确定第三个参数不存在(如使用 null 所意图的那样),那么它就不再是三元组,而是一对。只需保持简单,使用一个 Pair 类即可。
英文:
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.
答案3
得分: 5
Java不支持“optional”或渐进式类型。您可以尝试创建一个子类,将元数据默认设置为null,即NoMetadataTriple<K,V>,或者像其他答案中提到的那样将Void用于M。
Void "类型" 不能被实例化。它基本上是void(输出参数)作为一个Class。
英文:
Java does not support "optional" or gradual typing. You can try creating a subclass that defaults metadata to null, i.e. NoMetadataTriple<K,V>, or give Void for M instead as mentioned in the other answer.
The Void "type" cannot be instantiated. It's basically void (the output parameter) as a Class.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论