user3251142
user3251142

Reputation: 175

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?

Upvotes: 0

Views: 188

Answers (3)

Makoto
Makoto

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 Integers 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

Judge Mental
Judge Mental

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

Eugene Ryzhikov
Eugene Ryzhikov

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

Related Questions