Reputation: 337
So I'm trying to get my program to sort an array using the methods given to us by the textbook but I can't figure out what the parameter wants.
This is the code given to us:
public static <T extends Comparable<T>> void sort(T[] a) {
final int N = a.length;
for (int i = 0; i < N; i++) {
for (int j = i; j > 0 && less(a[j], a[j-1]); j--) {
exch(a, j, j-1);
}
assert isSorted(a, 0, i);
}
assert isSorted(a);
}
And this is my program:
public static void main(String[] args){
double power = 0;
int i;
Random rand = new Random();
for (i=8;i<=18;i++){
power = Math.pow(2, i);
double[] doubleArray = new double[(int) power];
for(int j = 0;j<doubleArray.length;j++) doubleArray[j] = rand.nextInt();
Insertion.sort(doubleArray);
}
}
Here I'm attempting create a main loop that iterates over the lengths that are powers of 2 from 28 to 218. Inside the loop,I randomly generate an array of integers of that length and call the sort on that array.(The sort method is in the class Insertion which is why it says Insertion.sort)
To my understanding the sorting method was made for arrays but the way it's written Eclipse is giving me an error saying that "The method sort(T[]) in the type Insertion is not applicable for the arguments (double[])".
Upvotes: 1
Views: 631
Reputation: 840
You can not use array of primitive type as argument for sort(T[])
because primitives do not implement Comparable
. Use wrapper types for primitives like Double
, Integer
.
public static void main(String[] args){
double power = 0;
int i;
Random rand = new Random();
for (i=8;i<=18;i++){
power = Math.pow(2, i);
Integer[] integerArray = new Integer[(int) power];
for(int j = 0;j<integerArray.length;j++) integerArray[j] = rand.nextInt();
Insertion.sort(integerArray);
}
}
Upvotes: 0
Reputation: 5949
You need to pass an array Objects, where the objects are of the same type and implement the Comparable interface to themselves.
The primitive double does not implement Comparable. But Double does.
Double implements Comparable<Double>
.
Upvotes: 0
Reputation: 347234
Primitives (double
) can't used with generics, it's expecting some type of Object
. Also double
is not Comparable
(it does not implement the required interface
...because it's a primitive).
You could, instead use Double
, for example...
for (i = 8; i <= 18; i++) {
power = Math.pow(2, i);
Double[] doubleArray = new Double[(int) power];
for (int j = 0; j < doubleArray.length; j++) {
doubleArray[j] = (double)rand.nextInt();
}
sort(doubleArray);
}
As it's both an Object
and implements Comparable
Upvotes: 1
Reputation: 8653
<T extends Comparable<T>>
simply means that T has to be of type Comparable at least. However, Comparable is also Generic, so you have to specify the type of Comparable as well, which is with the type T.
Classes of collections, and wrapper classes for primitive types satisfy this condition, so you can use any of them.
Upvotes: 0