简体   繁体   中英

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}. How would I create this T[] a and how would I call this method if I wanted to test it? 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 . 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 . Since Integer implements Comparable , this should work.

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). 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).

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[] vals = new Integer[]{5,2,7,3,8,9};

The above is possible due to autoboxing, and that int is assignment compatible with Integer .

Now, if you want to call it, you now pass in the necessary arguments to it.

qsort(vals, 0, 10);  // for instance

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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