简体   繁体   English

我可以像在 C# 中一样在 Java 中通过泛型类型重载类吗?

[英]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
}

I just want to create a class that just contains value of every generic type.我只想创建一个只包含每个泛型类型的值的类。 Like Tuple in C#:就像 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);

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> .因此,您根本不能拥有Tuple<int> (至少现在还没有,正在开发中),但需要使用Tuple<Integer>

Furthermore, Java does not allow overloading a class, at all.此外,Java 根本不允许重载类。 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 ).在 Java 14 中,我们获得了 Records 形式的名义元组作为预览功能( 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:相关阅读:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM