1

I want to implement this class to receive different types of arrays, like String, int, double, etc:

public class BubbleSort<T extends Comparable<T>> {

private T [] A;
public BubbleSort(T [] A) {
    this.A = A;
}

public void bubbleSort() {
    for (int i = 0; i < this.A.length; i++) {
        for (int j = 0; j < this.A.length - 1; j--) {
            if (this.A[j].compareTo(this.A[j - 1]) < 0) {
                T aux = this.A[j];
                this.A[j] = this.A[j - 1];
                this.A[j - 1] = aux;
            }
        }
    }
}

But when I'm creating an object of that class like this:

double A[] = { 3, 2, 4, 6, 7, 1, 2, 3 };    
BubbleSort bs = new BubbleSort(A);

I get an error that tell me the constructor of BubbleSort(double[]) is not defined. I think I'm doing something wrong with the generic type class and i need some help.

Cumps.

arturataide
  • 363
  • 2
  • 11

1 Answers1

3

You need to parameterize BubbleSort and use an array of a reference type, not a primitive type (since generics only works with reference types):

Double[] A = { 3d, 2d, 4d, 6d, 7d, 1d, 2d, 3d };    // notice Double ref. type
BubbleSort<Double> bs = new BubbleSort<Double>(A);  // notice <Double> type param.

Also notice that I've attached [] to the type of the array, which is Double. It is also valid to attach it to the variable name as you have done, but it is more conventional to attach it to the type.

arshajii
  • 127,459
  • 24
  • 238
  • 287
  • Thank you very much.. It worked as I expected. Thanks. – arturataide Jun 12 '14 at 01:55
  • I also find it easier to read the data type with the `[]` attached to the type of the array. You can know instantly that this variable is an array of the given type. I have no idea why Java allows attaching the `[]` to the variable name. It's confusing to distinguish between `Double A` and `Double A[]`. – ADTC Jun 12 '14 at 01:56
  • If you need to convert primitive arrays (in the event you're receiving a primitive array and you don't have the control to change the sender logic to send a reference type array), take a look at this question: [Cast primitive type array into object array in java](http://stackoverflow.com/questions/5606338/cast-primitive-type-array-into-object-array-in-java) – ADTC Jun 12 '14 at 02:04