[英]Passing int array in a Generic class
When i create a generic class object , why do i have to pass array of Integer type and not int type ? 当我创建一个通用类对象,为什么我要通过整型数组,而不是整型 ? If the typed parameter can be only reference type , then why does passing an int variable work but not int array ? 如果typed参数只能是引用类型,那么为什么传递int变量而不是int数组有效?
class GenericA<T extends Number> {
T arr[];
GenericA(T o[]) {
arr = o;
}
double average() {
double sum = 0;
for (int i = 0; i < arr.length; i++)
sum = sum + arr[i].doubleValue();
double average1 = sum / arr.length;
//System.out.println("the average is" +average);
return average1;
}
boolean sameAvg(GenericA<?> ob) {
if (average() == ob.average())
return true;
return false;
}
}
class GenericB {
public static void main(String[] args) {
Integer inum[] = {1, 2, 3, 4, 5}; //this cannot be int
Double inum1[] = {1.0, 2.0, 3.0, 4.0, 5.0}; //cannot be double
GenericA<Integer> ob = new GenericA<Integer>(inum);
GenericA<Double> ob1 = new GenericA<Double>(inum1);
boolean a = ob.sameAvg(ob1);
System.out.println(a);
}
}
The fact that Java generics do not support primitives (eg int
) is due to the JVM's implementation. Java泛型不支持原语(例如int
)的事实是由于JVM的实现。 Basically they aren't true generics like in C# - the information about the type is lost at runtime (search for type erasure problem
). 基本上,它们不是像C#中那样的真正泛型-有关类型的信息会在运行时丢失(搜索type erasure problem
)。 Thus Java generics are basically casts to and from Object
s under the hood. 因此,Java泛型基本上是在Object
与Object
强制转换的。
For example: 例如:
List<Integer> l = new List<Integer>();
...
Integer i = l.get(0);
would actually become 实际上会变成
List l = new List();
Integer i = (Integer) l.get(0);
at runtime. 在运行时。
Passing an int
variable where Integer
is expected is possible due to auto-boxing. 由于自动装箱,可能会在可能需要Integer
地方传递int
变量。
However, passing an int[]
where Integer[]
is expected is not possible, since there's no auto-boxing for arrays of primitive types. 但是,不可能通过传递期望Integer[]
的int[]
来实现,因为没有自动装箱用于原始类型的数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.