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.

7
  • 1
    Also, generics don't work with primitive types. Commented Jun 12, 2014 at 1:36
  • @SotiriosDelimanolis the posto you have mentioned don't answer my question Commented Jun 12, 2014 at 1:43
  • Why do you think so? Do you know what a raw type is now? Do you see how it applies to your situation? Commented Jun 12, 2014 at 1:44
  • @SotiriosDelimanolis So it's impossible what i'm trying to do? Commented Jun 12, 2014 at 1:48
  • 1
    You can use a Double[]. Commented Jun 12, 2014 at 1:50

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very much.. It worked as I expected. Thanks.
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[].
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.