英文:
Can I overload class by generic type in java like in C#?
问题
public class A<T> {
// do something
}
public class A<T, B> {
// do something
}
我只想创建一个类,它只包含每种泛型类型的值。类似 C# 中的 Tuple:
Tuple<int> intContainer = new Tuple<int>(5);
Tuple<int, int> twoIntContainer = new Tuple<int, int>(5, 5);
Tuple<int, int, int> threeIntContainer = new Tuple<int, int, int>(5, 5, 5);
英文:
public class A<T>
{
// do something
}
public class A<T, B>
{
// do something
}
I just want to create a class that just contains value of every generic type. Like Tuple in C#:
Tuple<int> intContainer = new Tuple<int>(5);
Tuple<int, int> twoIntContainer = new Tuple<int, int>(5, 5);
Tuple<int, int, int> threeIntContainer = new Tuple<int, int, int>(5, 5, 5);
答案1
得分: 4
首先,你不能将原始类型作为泛型参数,只能使用引用类型。因此,你不能完全使用 Tuple<int>
(至少目前还不能,正在进行中),但需要使用 Tuple<Integer>
。
此外,Java 不允许对一个类进行重载。你不能为一个类定义两个不同的定义,因此不能针对同一个类使用不同数量的泛型参数。但你可以对该类进行子类化,然后在子类中添加更多的泛型参数,这样做有其优缺点。
在 Java 14 中,我们以预览特性的形式获得了名义上的元组,即记录类型(在 Java 15 中进行了第二轮预览)。因此,创建可以容纳所需元素的临时数据结构变得更加容易,极大地减少了对通用元组类型的需求。
相关阅读:
英文:
First things first, you can not have primitive types as generic parameters, only reference types. Thus, you can not have Tuple<int>
at all (at least not yet, thats in the works), but need to use Tuple<Integer>
.
Furthermore, Java does not allow overloading a class, at all. You can not have two definitions for a class, thus you can not have the same class with a different amount of generic parameters.
You can subclass the class, though, and add more generic parameters to the subclass, with all the pros and cons that has.
With Java 14, we got nominal tuples in the form of Records as a preview feature (2nd preview in Java 15). Thus, creating ad-hoc data structures that can hold the required elements has become much easier, greatly reducing the demand for general-purpose tuple types.
Related reading:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论