Reputation: 175
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?
Upvotes: 0
Views: 188
Reputation: 106430
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
Upvotes: 1
Reputation: 5239
qSort( new Integer[] { 5,2,7,3,8,9 }, 0, 5 );
The important thing to notice is that the type of the first argument is Integer[]
, not int[]
.
Upvotes: 1
Reputation: 17359
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.
Upvotes: 1