Search code examples
javabubble-sort

Create a class in java that can receive different types


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.


Solution

  • 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.