简体   繁体   English

我可以在 java 中的变量上应用泛型吗?

[英]can i apply generics on a variable in java?

in java we can apply generics on a class and methods as shown below在java中,我们可以在类和方法上应用泛型,如下所示

class Sample<T>{}
public <T,E> void test(T x, E y){}

this helps us write generic algorithms , help us reuse the same code for multiple inputs ,similarly can we apply generics on primitive variables??这有助于我们编写泛型算法,帮助我们为多个输入重用相同的代码,同样我们可以在原始变量上应用泛型吗?? if it is possible we can reuse the same variable again and again for different inputs , i know如果有可能我们可以一次又一次地为不同的输入重用同一个变量,我知道

class Sample<T>{public T temp;}

is possible.是可能的。

but the question is但问题是

class Sample{public <T> T temp;}

is this possible这可能吗

No it's not, it wouldn't be possible to tell what type temp is, so it wouldn't help the compiler restrict anything (that is the point of generics), or tools to make any suggestions.不,它不是,不可能知道 temp 是什么类型,所以它不会帮助编译器限制任何东西(这是泛型的重点),或提供任何建议的工具。

You can't get better in this case than making temp an Object.在这种情况下,没有比使 temp 成为 Object 更好的方法了。 (or use your second example) (或使用您的第二个示例)

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

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