How do I create a Java class that is like: Minhaclasse<T extends Comparable<T>?

Asked

Viewed 31 times

-2

I am trying to start a class that is a Bubble Sort that extends a class called Comparable. My code is like this:

public final class BubbleSortPassPerItem<T extends Comparable<T>> implements Sorter<T> {
    public void sort(final T[] items) {
        for (int pass=0; pass<items.length; pass++) {
            for (int i=0; i<items.length-1; i++) {
                if (items[i].compareTo(items[i+1])>0) {
                    final T item = items[i];
                    items[i] = items[i+1];
                    items[i+1] = item;
                }
            }
        }
    }
}

I don’t quite understand how these parameterized classes work. How do I start this class in the Main method?

1 answer

1


The initialization logic of your example is the same as when an array is created using Generics. You will put the name of the Class that meets the inheritance criteria you mentioned within <> It’ll look something like this:

SuaClasseBubbleSort<ClasseQueHerdaDeComparable> bubbleSort = new SuaClasseBubbleSort<>();

The class you enter within <> must have implemented the Comparable interface.

I recommend doing a web search on Java Generics, the subject is easy to understand.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.