[英]How do I call a method with a generic type T[] as an argument?
Ok, say I have this method header: 好的,说我有这个方法头:
public static <T extends Comparable<T>> void qSort(T[] a, int p, int q)
Say I wanted T[] a to hold {5,2,7,3,8,9}. 假设我想让T [] a保持{5,2,7,3,8,9}。 How would I create this T[] a and how would I call this method if I wanted to test it?
我将如何创建此T [] a,如果要测试该方法,将如何调用该方法? I'm a little confused.
我有点困惑。
I've tried updating my question to make it more clear. 我试图更新我的问题以使其更加清楚。 If something isn't clear then please post a comment.
如果不清楚,请发表评论。
Anything? 有什么事吗
Java has a feature called autoboxing . Java具有称为自动装箱的功能 。 Your example would look like
你的例子看起来像
qSort( new Integer[]{5,2,7,3,8,9}, p, q)
Notice that the array is not based on primitive type int
, but int
values inside are "autoboxed" automatically by compiler into Integer
. 请注意,该数组不是基于原始类型
int
,而是内部的int
值由编译器自动“自动装箱”为Integer
。 Since Integer
implements Comparable
, this should work. 由于
Integer
实现了Comparable
,这应该可以工作。
qSort( new Integer[] { 5,2,7,3,8,9 }, 0, 5 );
需要注意的重要一点是,第一个参数的类型是Integer[]
,而不是int[]
。
First things first: you can't use a primitive array to hold elements that are expected in an object array; 首先,您不能使用原始数组来保存对象数组中期望的元素; they're incompatible types.
它们是不兼容的类型。
Remember that the generic type parameter T
is always an Object
(with respect to its bounds). 请记住,泛型参数
T
始终是一个Object
(相对于其边界)。 If you want to get any type of numerical reference in there, then you should be also be bound to Number
(which is the superclass of all of the numerical wrapper classes). 如果要在其中获取任何类型的数字引用,则还应将其绑定到
Number
(它是所有数字包装器类的超类)。
public static <T extends Number & Comparable<T>> void qSort(T[] a, int p, int q)
Now, as for the array you'll be passing in...it will have to be an array of Integer
s instead of int[]
. 现在,对于要传递的数组,它必须是
Integer
的数组,而不是int[]
。
Integer[] vals = new Integer[]{5,2,7,3,8,9};
The above is possible due to autoboxing, and that int
is assignment compatible with Integer
. 由于自动装箱,上述操作是可能的,并且
int
与Integer
分配兼容 。
Now, if you want to call it, you now pass in the necessary arguments to it. 现在,如果要调用它,则现在将必需的参数传递给它。
qsort(vals, 0, 10); // for instance
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.