[英]Can you use primitive types for generic parameters in a class or method?
我正在写一篇关于泛型的简短文章,而我在Java中并没有真正使用它们。 我想知道原始类型是否可以用作通用变量中的参数类型。 我无法使其与具有通用类型的通用参数一起编译。
问题:对于泛型如何处理原始数据类型,我有些不确定。 有人可以举例说明我如何必须声明不同的方法,而不必在Integer中将强制类型转换添加到int类型,以及是否可以在类声明中使用原始Java数据类型。
DDHGeneric<int,int,int,int> t = new DDHGeneric<int,int,int,int>();
有没有办法做到这一点?
以下声明也不编译。 我确实知道,从对泛型的了解来看,使用原始数据类型和用户定义的类之间存在差异。
DDHGeneric<int, int, int, int> temp2 = new DDHGeneric<int, int, int, int>();
类:
public class DDHGeneric<T,K,Bigfoot,Pizza> {
T a;
K n;
Bigfoot u;
public DDHGeneric() {
}
private <rapper> void myMethod(rapper y) {
int temp = y; <--Errors out on this line as will.
}
public <Pizza> void myAddition(Pizza a, Pizza b) {
}
private <K> void me(K a, K b, K c) {
}
public static void main(String[] args) {
DDHGeneric<int, Integer, Integer, Integer> temp = new DDHGeneric<int, Integer, Integer, Integer>();
temp.myAddition(5, 4);
temp.a = "Test this string!" ;
}
}
没有。
泛型不代表原始。 它们旨在表示对象(因为泛型类型都隐式扩展了Object
)。
您可以使用所需的原始类的包装器变体来实现相同的效果。
DDHGeneric<Integer, Integer, Integer, Integer> t = new DDHGeneric<>();
这是“ 为什么使用泛型?”的简短摘录。 ,可在Java Trail中找到:
简而言之,泛型在定义类,接口和方法时使类型 (类和接口)成为参数。
泛型仅采用原始类,而不采用原始数据类型。
对于每种数据类型,使用其对应的类
DDHGeneric<int,int,int,int> t = new DDHGeneric<int,int,int,int>();
可以用作
DDHGeneric<Integer, Integer, Integer, Integer> t = new DDHGeneric<Integer, Integer, Integer, Integer>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.