1

My computer science teacher gave me a challenge to create a function that can take in an array of any object and sort it using bubble sort. Since the Object class is the parent class of all classes, I thought of taking in an array of Objects but I can't really sort it since the Object class doesn't have a comparable. I'm kind of stuck right now because I don't know what to pass in to the function. My teacher said that I should pass in a Comparable interface but I'm afraid I don't know enough to know what he means by that.

This is what I tried but I know it doesn't work:

public static void bubble(Object arr[]) {
    for (int i = 0; i < arr.length - 1; i ++) {
        for (int j = 0; j < arr.length - i - 1; j++) {
            if (arr[j].compareTo(arr[j + 1]) > 0) {
                Object temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}

I don't know much about Java so any help is greatly appreciated, thank you!

Kayla Wang
  • 25
  • 1
  • 4
  • 2
    Try `public static > void bubble(T[] arr)` or `public static void bubble(T[] arr, Comparator comp)` (I think your teacher wants the first one though). Or maybe you weren't expected to find the first one and should do `public static void bubble(Comparable[] arr)`. – Elliott Frisch Apr 29 '20 at 19:01
  • I got that to work, thank you so much! – Kayla Wang Apr 29 '20 at 19:27

1 Answers1

1

You are on the right track with your confusion! Indeed, not all objects have a comparator, and are thus incomparable; it sounds like your teacher wants your method to reject objects like this.

You can enforce the bubble method to only accept Comparable objects as follows:

public static <T extends Comparable<? super T>> void bubble(T[] arr)

This method header takes advantage of a java concept called generics-- basically a variable which represents a type, instead of an object. In this case, your generic variable is T. Thus, if the method was called with bubble(new Box[]), then T would represent the type Box.

The <T extends Comparable<? super T>> says: "T must implement Comparable that can sort T" You can read more here.

McKay M
  • 448
  • 2
  • 8