Can I overload class by generic type in java like in C#?

huangapple go评论65阅读模式
英文:

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&lt;T&gt;
{
    // do something
}
public class A&lt;T, B&gt;
{
    // do something
}

I just want to create a class that just contains value of every generic type. Like Tuple in C#:

Tuple&lt;int&gt; intContainer = new Tuple&lt;int&gt;(5);
Tuple&lt;int, int&gt; twoIntContainer = new Tuple&lt;int, int&gt;(5, 5);
Tuple&lt;int, int, int&gt; threeIntContainer = new Tuple&lt;int, int, int&gt;(5, 5, 5);

答案1

得分: 4

首先,你不能将原始类型作为泛型参数,只能使用引用类型。因此,你不能完全使用 Tuple&lt;int&gt;(至少目前还不能,正在进行中),但需要使用 Tuple&lt;Integer&gt;

此外,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&lt;int&gt; at all (at least not yet, thats in the works), but need to use Tuple&lt;Integer&gt;.

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:

huangapple
  • 本文由 发表于 2020年10月15日 22:11:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/64373467.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定