Search code examples
javagenericscollectionscomparable

Collections sort generics types java


I was looking for an answer to my question for so long. I found loads of similar topics but I still do not know what to do.

I have a class where I want to store objects in sorted ArrayList.

For instance, I created this class:

public class Kwadrat implements Comparable<Kwadrat> {

    private int a;

    public Kwadrat(int a){
        this.a = a;
    }

    public int get_size(){
        return a*a;
    }

    public int compareTo(Kwadrat b){
        if(b.get_size() > get_size()){
            return -1;
        }
        if(b.get_size() < get_size()){
            return 1;
        }
        return 0;
    }
}

And here is my Sort class:

public class Sort <T> {
    ArrayList<T> arraylist;

    public Sort(){
        arraylist = new ArrayList<T>();
    }


    public void add(T element){

        arraylist.add(element);

       Collections.sort(arraylist);



    }
}

Collections.sort(arraylist); still tells me that "no instance(s) of type variable(s) T exists so that T conforms to Comparable<? super T>".


Solution

  • Your Sort class currently has no bounds on its type parameter T, so it could be any type, even a type that isn't Comparable. It would accept Object, which is not Comparable. Because there is no bounds, and because the compiler sees that there are bounds on what can be passed to the single-arg Collections.sort method, there is your compiler error.

    You should create the same bounds on T that Collections.sort expects.

    public class Sort <T extends Comparable<T>> {
    

    Or even better:

    public class Sort <T extends Comparable<? super T>> {