0

I have a generic class that contains an array. That array can be any data type(Double,Integer,String...) and I am trying to learn how could I sort this array just after constructed. I've wrote a sorting method for sorting the array after constructed. But, java inhibits sorting generic array with mysort method due to mismatch.

public class SortingTest<E> {

    private E[] array;
    //constructor which creates an object and sorts its array via mysort method.
    public SortingTest(E[] N){
        this.array = N;
        mysort(this.array);
    }
    //sorts array.
    private static<T extends Comparable<T>> void mysort(T[] arr){
        T temp = null;
        //Bubble sort increasing order.
        for(int j=0; j<arr.length; j++){
            for(int i=1; i<arr.length; i++){
                if(arr[i-1].compareTo(arr[i]) > 0 ){
                    temp = arr[i-1];
                    arr[i-1] = arr[i];
                    arr[i] = temp;

                }
            }
        }
    }
}

How can I overcome this problem? Any help is appreciated.

3
  • Think about what you are passing to mysort(..) in your constructor. What type is it? Does it match the bounds set by the method. Commented Jun 5, 2014 at 17:36
  • It can be any type as I said. The problem , which arise from didn't known implementation of Comparable interface, is solved by @Luiggi Mendoza Thank you very much for help. Commented Jun 5, 2014 at 17:41
  • 1
    As an aside, note that generics and arrays don't play well together. You'll have a much better time working with Lists and the rest of the Collections Framework. Commented Jun 5, 2014 at 17:41

1 Answer 1

3

mysort method requires generic element T implements Comparable<T>, but generic E doesn't declare that implements Comparable<E>. Change the declaration to:

public class SortingTest<E extends Comparable<? super E>> {
    //rest of your code...
}
Sign up to request clarification or add additional context in comments.

3 Comments

I think it would be better if you did "E extends Comparable<? super E>" to cover the case where the parent class implements Comparable. Sorry if that's nit-picky.
What is the difference between them? Does using super keyword make any advantages? @pscuderi
@Sixie it means that if the generic class E extends from another class SE and SE is the class that implements Comparator<SE>, then E won't need to implement Comparator<E> itself because already implements Comparator<SE>.

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.